List of usage examples for org.apache.shiro SecurityUtils setSecurityManager
public static void setSecurityManager(SecurityManager securityManager)
From source file:com.zhengxuetao.shiro.LoginFromRealm.java
public void testLogin(String account, String pwd) { //1?? SecurityManager realm Ini ?? SecurityManager Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro_realm.ini"); //2? SecurityManager SecurityUtils SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); //3? Subject ???/?? Token?/? Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(account, pwd); try {/*from w w w . jav a 2s .com*/ //4??? subject.login(token); } catch (AuthenticationException e) { //5?? System.out.println(account + ";" + e.getMessage()); throw e; } if (subject.isAuthenticated()) { //? System.out.println(account + "?"); } //6? subject.logout(); }
From source file:de.scoopgmbh.copper.monitoring.server.SecureLoginService.java
License:Apache License
public SecureLoginService(Realm realm) { super(); SecurityUtils.setSecurityManager(new DefaultSecurityManager(realm)); }
From source file:de.triology.blog.complexspermissions.demo.Demo.java
License:Open Source License
@BeforeClass public static void setUpShiro() throws Exception { Realm realm = new ComplexPermissionRealm(); SecurityManager securityManager = new DefaultSecurityManager(realm); SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); subject.login(new UsernamePasswordToken("user", "password")); assertTrue(subject.isAuthenticated()); }
From source file:eu.forgestore.ws.util.ShiroUTValidator.java
License:Apache License
public void setSecurityManager(SecurityManager securityManager) { logger.info("=============== setSecurityManager ==================================================="); this.securityManager = securityManager; SecurityUtils.setSecurityManager(this.securityManager); }
From source file:graphene.web.test.unit.LDAPTest.java
License:Apache License
public void testLogin() { // 1./*from ww w.j a v a 2 s .co m*/ final Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( "classpath:shiro.ini"); // 2. final org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); // 3. SecurityUtils.setSecurityManager(securityManager); }
From source file:io.github.howiefh.console.ShiroDemo.java
public static void main(String[] args) { log.info("My First Apache Shiro Application"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // ??://from w w w .j a v a2s. co m Subject currentUser = SecurityUtils.getSubject(); // ? Session Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); } // ??? if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... ? catch (AuthenticationException ae) { // ?? } } // ?: // ??? ( username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); // : if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } // ?? (? instance-level ) if (currentUser.isPermitted("lightsaber:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } // (?)??: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } // ? - t! currentUser.logout(); System.exit(0); }
From source file:it.freedomotic.security.AuthImpl.java
License:Open Source License
@Override public void initBaseRealm() { DefaultSecurityManager securityManager = null; if (!realmInited && config.getBooleanProperty("KEY_SECURITY_ENABLE", true)) { baseRealm.setName(BASE_REALM_NAME); baseRealm//from w w w. j ava 2 s .c o m .setResourcePath(new File(Info.PATH_WORKDIR + "/config/security.properties").getAbsolutePath()); baseRealm.init(); pluginRealm.init(); securityManager = new DefaultSecurityManager(); //securityManager = injector.getInstance(DefaultSecurityManager.class); realmCollection.add(baseRealm); realmCollection.add(pluginRealm); securityManager.setRealms(realmCollection); realmInited = true; } SecurityUtils.setSecurityManager(securityManager); }
From source file:kamsky.app.Main.java
public static void main(String[] args) { log.info("My First Apache Shiro Application"); IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); }//from w w w . jav a 2 s . c o m // let's login the current user so we can check against roles and permissions: if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... catch more exceptions here (maybe custom ones specific to your application? catch (AuthenticationException ae) { //unexpected condition? error? } } //say who they are: //print their identifying principal (in this case, a username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }
From source file:lib.Global.java
License:Open Source License
@Override public void onStart(Application app) { log.info("Graylog web interface version {} starting up.", Version.VERSION); final String appSecret = app.configuration().getString("application.secret"); if (appSecret == null || appSecret.isEmpty()) { log.error("Please configure application.secret in your conf/graylog-web-interface.conf"); throw new IllegalStateException("No application.secret configured."); }/*from ww w .j av a2 s.c om*/ if (appSecret.length() < 16) { log.error( "Please configure application.secret in your conf/graylog-web-interface.conf to be longer than 16 characters. Suggested is using pwgen -N 1 -s 96 or similar"); throw new IllegalStateException( "application.secret is too short, use at least 16 characters! Suggested is to use pwgen -N 1 -s 96 or similar"); } final String graylog2ServerUris = app.configuration().getString("graylog2-server.uris", ""); if (graylog2ServerUris.isEmpty()) { log.error("graylog2-server.uris is not set!"); throw new IllegalStateException("graylog2-server.uris is empty"); } final String[] uris = graylog2ServerUris.split(","); if (uris.length == 0) { log.error("graylog2-server.uris is empty!"); throw new IllegalStateException("graylog2-server.uris is empty"); } final URI[] initialNodes = new URI[uris.length]; int i = 0; for (String uri : uris) { try { initialNodes[i++] = new URI(uri); } catch (URISyntaxException e) { log.error("Invalid URI in 'graylog2-server.uris': " + uri, e); } } final String timezone = app.configuration().getString("timezone", ""); if (!timezone.isEmpty()) { try { DateTools.setApplicationTimeZone(DateTimeZone.forID(timezone)); } catch (IllegalArgumentException e) { log.error("Invalid timezone {} specified!", timezone); throw new IllegalStateException(e); } } log.info("Using application default timezone {}", DateTools.getApplicationTimeZone()); // Dirty hack to disable the play2-graylog2 AccessLog if the plugin isn't there gelfAccessLog = app.configuration().getBoolean("graylog2.appender.send-access-log", false); final ObjectMapper objectMapper = buildObjectMapper(); Json.setObjectMapper(objectMapper); final List<Module> modules = Lists.newArrayList(); modules.add(new AbstractModule() { @Override protected void configure() { bind(URI[].class).annotatedWith(Names.named("Initial Nodes")).toInstance(initialNodes); bind(Long.class).annotatedWith(Names.named("Default Timeout")) .toInstance(org.graylog2.restclient.lib.Configuration.apiTimeout("DEFAULT")); bind(ObjectMapper.class).toInstance(objectMapper); } }); modules.add(new ModelFactoryModule()); injector = Guice.createInjector(modules); // start the services that need starting final ApiClient api = injector.getInstance(ApiClient.class); api.start(); injector.getInstance(ServerNodesRefreshService.class).start(); // TODO replace with custom AuthenticatedAction filter RedirectAuthenticator.userService = injector.getInstance(UserService.class); RedirectAuthenticator.sessionService = injector.getInstance(SessionService.class); // temporarily disabled for preview to prevent confusion. // LocalAdminUserRealm localAdminRealm = new LocalAdminUserRealm("local-accounts"); // localAdminRealm.setCredentialsMatcher(new HashedCredentialsMatcher("SHA2")); // setupLocalUser(api, localAdminRealm, app); Realm serverRestInterfaceRealm = injector.getInstance(ServerRestInterfaceRealm.class); final DefaultSecurityManager securityManager = new DefaultSecurityManager( Lists.newArrayList(serverRestInterfaceRealm)); // disable storing sessions (TODO we might want to write a session store bridge to play's session cookie) final DefaultSessionStorageEvaluator sessionStorageEvaluator = new DefaultSessionStorageEvaluator(); sessionStorageEvaluator.setSessionStorageEnabled(false); final DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO(); subjectDAO.setSessionStorageEvaluator(sessionStorageEvaluator); securityManager.setSubjectDAO(subjectDAO); final Authenticator authenticator = securityManager.getAuthenticator(); if (authenticator instanceof ModularRealmAuthenticator) { ModularRealmAuthenticator a = (ModularRealmAuthenticator) authenticator; a.setAuthenticationStrategy(new RethrowingFirstSuccessfulStrategy()); a.setAuthenticationListeners( Lists.<AuthenticationListener>newArrayList(new PlayAuthenticationListener())); } SecurityUtils.setSecurityManager(securityManager); }
From source file:local.zcw.demo.shiro.shiro.hello.Client.java
public static void main(String[] args) { //??SecurityManager Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); //securityManger? SecurityUtils.setSecurityManager(securityManager); //???//w ww . j a v a 2s. c o m Subject currentUser = SecurityUtils.getSubject(); //?session??web Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); } //??? if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.info("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); } // ... catch more exceptions here (maybe custom ones specific to your application? catch (AuthenticationException ae) { //unexpected condition? error? } } //say who they are: //print their identifying principal (in this case, a username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }