List of usage examples for org.apache.shiro SecurityUtils setSecurityManager
public static void setSecurityManager(SecurityManager securityManager)
From source file:com.ikanow.aleph2.security.service.ShiroSecurityTest.java
License:Apache License
@Test public void test() { logger.info("My First Apache Shiro Application"); Factory<SecurityManager> 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")) { logger.info("Retrieved the correct value! [" + value + "]"); }/*from w ww . ja v a 2s. co m*/ //test a role before login: if (currentUser.hasRole("schwartz")) { logger.info("Role Schwartz before login!"); } else { logger.info("No Role before login."); } // 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) { logger.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { logger.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { logger.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): logger.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { logger.info("May the Schwartz be with you!"); } else { logger.info("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:weild")) { logger.info("You may use a lightsaber ring. Use it wisely."); } else { logger.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { logger.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { logger.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); //System.exit(0); }
From source file:com.imos.sample.Quickstart.java
License:Apache License
public static void main(String[] args) { // The easiest way to create a Shiro SecurityManager with configured // realms, users, roles and permissions is to use the simple INI config. // We'll do that by using a factory that can ingest a .ini file and // return a SecurityManager instance: // Use the shiro.ini file at the root of the classpath // (file: and url: prefixes load from files and urls respectively): Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); // for this simple example quickstart, make the SecurityManager // accessible as a JVM singleton. Most applications wouldn't do this // and instead rely on their container configuration or web.xml for // webapps. That is outside the scope of this simple quickstart, so // we'll just do the bare minimum so you can continue to get a feel // for things. SecurityUtils.setSecurityManager(securityManager); // Now that a simple Shiro environment is set up, let's see what you can do: // get the currently executing user: Subject currentUser = SecurityUtils.getSubject(); ///home/alok/Tools/netbean_dev_workspace/AllProjects/SampleShiro/src/main/java/com/imos/sample/Quickstart.java // Do some stuff with a Session (no need for a web or EJB container!!!) Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); session.setTimeout(12000);/*from w ww. jav a 2 s . c o m*/ System.out.println("Id : " + session.getId()); System.out.println("Host : " + session.getHost()); System.out.println("StartTime : " + session.getStartTimestamp()); System.out.println("Timeout : " + session.getTimeout()); String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); } // 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!"); } try { System.out.println("Delay for 10 sec"); Thread.sleep(10000); } catch (InterruptedException ex) { log.error(ex.getMessage()); } try { System.out.println("LastAccess : " + session.getLastAccessTime()); //all done - log out! currentUser.logout(); } catch (Exception e) { System.out.println(e.getMessage()); } // currentUser = SecurityUtils.getSubject(); System.out.println("\nNew Session"); session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); System.out.println("Id : " + session.getId()); System.out.println("Host : " + session.getHost()); System.out.println("StartTime : " + session.getStartTimestamp()); System.out.println("Timeout : " + session.getTimeout() / 1000); // 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? } try { System.out.println("Delay for 5 sec"); Thread.sleep(5000); } catch (InterruptedException ex) { log.error(ex.getMessage()); } try { System.out.println("Last Access : " + session.getLastAccessTime()); //all done - log out! currentUser.logout(); } catch (Exception e) { System.out.println(e.getMessage()); } } System.exit(0); }
From source file:com.imos.sample.SampleShiroOne.java
public static void main(String[] args) { System.out.println("s"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); //Example using most common scenario: //String username and password. Acquire in //system-specific manner (HTTP request, GUI, etc) UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); //?Remember Me? built-in, just do this: token.setRememberMe(true);/*from w ww . j ava 2 s. c o m*/ //With most of Shiro, you'll always want to make sure you're working with the currently //executing user, referred to as the subject Subject currentUser = SecurityUtils.getSubject(); //Authenticate the subject by passing //the user name and password token //into the login method currentUser.login(token); try { currentUser.login(token); } catch (UnknownAccountException uae) { } catch (IncorrectCredentialsException ice) { } catch (LockedAccountException lae) { } catch (ExcessiveAttemptsException eae) { } catch (AuthenticationException ae) { } }
From source file:com.imos.sample.SampleShiroTwo.java
public static void main(String[] args) { System.out.println("s"); Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( "classpath:shiro.ini"); org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); //Example using most common scenario: //String username and password. Acquire in //system-specific manner (HTTP request, GUI, etc) UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); // UsernamePasswordToken token = new UsernamePasswordToken("", ""); //?Remember Me? built-in, just do this: token.setRememberMe(true);/* w ww.j ava 2s . com*/ //With most of Shiro, you'll always want to make sure you're working with the currently //executing user, referred to as the subject Subject currentUser = SecurityUtils.getSubject(); //Authenticate the subject by passing //the user name and password token //into the login method currentUser.login(token); try { currentUser.login(token); } catch (UnknownAccountException uae) { } catch (IncorrectCredentialsException ice) { } catch (LockedAccountException lae) { } catch (ExcessiveAttemptsException eae) { } catch (AuthenticationException ae) { } }
From source file:com.infinities.skyport.vnc.impl.LocalWebsockifyService.java
License:Apache License
@Override public void initialize() { sslSetting = SSLSetting.OFF;/*from w ww. j ava2s . c om*/ boolean requireSSL = configuration.isRequireSSL(); boolean enableSSL = configuration.isEnableSSL(); String keystore = configuration.getKeystoreFile(); String keystoreType = configuration.getKeystoreType(); String keystorePassword = configuration.getKeystorePass(); String keystoreKeyPassword = configuration.getKeystoreKeyPass(); if (requireSSL) sslSetting = SSLSetting.REQUIRED; else if (enableSSL) sslSetting = SSLSetting.ON; if (sslSetting != SSLSetting.OFF) { if (keystore == null || keystore.isEmpty()) { throw new IllegalArgumentException("No keystore specified."); } if (keystorePassword == null || keystorePassword.isEmpty()) { throw new IllegalArgumentException("No keystore password specified."); } if (keystoreKeyPassword == null || keystoreKeyPassword.isEmpty()) { keystoreKeyPassword = keystorePassword; } try { WebsockifySslContext.validateKeystore(keystoreType, keystore, keystorePassword, keystoreKeyPassword); } catch (Exception e) { throw new IllegalStateException("Error validating keystore", e); } } if (sslSetting != SSLSetting.OFF) logger.debug("SSL is {}", (sslSetting == SSLSetting.REQUIRED ? "required." : "enabled.")); channelMap = new ConcurrentHashMap<String, Channel>(); SecurityUtils.setSecurityManager(securityManager); portFinder = new AvailablePortFinder(configuration.getMinPort(), configuration.getMaxPort()); }
From source file:com.jason.blog.infrastruture.shiro.Tutorial.java
/** * @param args// ww w. ja v a 2 s .c om */ public static void main(String[] args) { // The easiest way to create a Shiro SecurityManager with configured // realms, users, roles and permissions is to use the simple INI config. // We'll do that by using a factory that can ingest a .ini file and // return a SecurityManager instance: // Use the shiro.ini file at the root of the classpath // (file: and url: prefixes load from files and urls respectively): Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); // for this simple example quickstart, make the SecurityManager // accessible as a JVM singleton. Most applications wouldn't do this // and instead rely on their container configuration or web.xml for // webapps. That is outside the scope of this simple quickstart, so // we'll just do the bare minimum so you can continue to get a feel // for things. SecurityUtils.setSecurityManager(securityManager); // Now that a simple Shiro environment is set up, let's see what you can do: // 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 + "]"); } // 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:com.jf.javafx.services.Security.java
License:Open Source License
@Override protected void _initService() { authenticationRequired = appConfig.getBoolean("authentication.required", true); if (authenticationRequired) { try {// www.j a va2 s.com Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( "url:" + app.getConfig("shiro.ini").toURL().toString()); org.apache.shiro.mgt.SecurityManager sm = factory.getInstance(); SecurityUtils.setSecurityManager(sm); } catch (MalformedURLException ex) { Logger.getLogger(Security.class.getName()).log(Level.SEVERE, null, ex); } } }
From source file:com.junhuang.market.api.test.java
public static void main(String[] args) { /* MongoClient mongoClient=new MongoClient("localhost",27017); MongoDatabase database = mongoClient.getDatabase("test"); System.err.println(database.getName()); MongoCollection<Document> hello = database.getCollection("hello"); System.err.println(hello);*/ Logger log = LoggerFactory.getLogger(test.class); Factory factory = new IniSecurityManagerFactory("classpath:shiro.ini"); org.apache.shiro.mgt.SecurityManager securityManager = (org.apache.shiro.mgt.SecurityManager) factory .getInstance();//from w w w . j a va 2s . c o m SecurityUtils.setSecurityManager(securityManager); Subject subject = SecurityUtils.getSubject(); // 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")) { System.err.println("Retrieved the correct value! [" + value + "]"); } // 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) { System.err.println("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { System.err.println("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { System.err.println("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): System.err.println("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("admin")) { System.err.println("May the Schwartz be with you!"); } else { System.err.println("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:weild")) { System.err.println("You may use a lightsaber ring. Use it wisely."); } else { System.err.println("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { System.err.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { System.err.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }
From source file:com.jythonui.server.security.impl.SubjectCache.java
License:Apache License
private Result authenticate(SessionEntry se, String tokenS) { SecurityManager securityManager = constructManager(se.getRealm()); SecurityUtils.setSecurityManager(securityManager); Subject currentUser = buildSubject(); PasswordSecurityToken token = new PasswordSecurityToken(se.getUser(), se.getPassword(), se.getiCustom()); info(gMess.getMessN(ILogMess.AUTHENTICATEUSER, se.getUser(), se.getRealm())); try {//from ww w. ja v a 2s . c o m currentUser.login(token); } catch (UnknownAccountException uae) { info(gMess.getMess(IErrorCode.ERRORCODE3, ILogMess.AUTHENTICATENOUSER, se.getUser())); return null; } catch (IncorrectCredentialsException ice) { info(gMess.getMess(IErrorCode.ERRORCODE4, ILogMess.AUTHENTICATEINCORECTPASSWORD, se.getUser())); return null; } catch (LockedAccountException lae) { info(gMess.getMess(IErrorCode.ERRORCODE5, ILogMess.AUTHENTOCATELOCKED, se.getUser())); return null; } catch (AuthenticationException ae) { severe(gMess.getMess(IErrorCode.ERRORCODE6, ILogMess.AUTHENTICATEOTHERERROR, se.getUser(), ae.getMessage()), ae); ae.printStackTrace(); return null; } catch (UnknownSessionException ae) { info(gMess.getMess(IErrorCode.ERRORCODE22, ILogMess.AUTHENTICATEOTHERERROR, se.getUser(), ae.getMessage())); return null; } info(gMess.getMessN(ILogMess.OKAUTHENTICATED)); if (tokenS == null) { UUID i = UUID.randomUUID(); tokenS = i.toString(); iCache.put(tokenS, se); } CurrentSubject subS = new CurrentSubject(); subS.se = se; subS.sManager = securityManager; subS.currentUser = currentUser; lastS.set(subS); return new Result(currentUser, tokenS); }
From source file:com.lieve.online.shiro.Quickstart.java
License:Apache License
public static void main(String[] args) { // The easiest way to create a Shiro SecurityManager with configured // realms, users, roles and permissions is to use the simple INI config. // We'll do that by using a factory that can ingest a .ini file and // return a SecurityManager instance: // Use the shiro.ini file at the root of the classpath // (file: and url: prefixes load from files and urls respectively): Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); // for this simple example quickstart, make the SecurityManager // accessible as a JVM singleton. Most applications wouldn't do this // and instead rely on their container configuration or web.xml for // webapps. That is outside the scope of this simple quickstart, so // we'll just do the bare minimum so you can continue to get a feel // for things. SecurityUtils.setSecurityManager(securityManager); // Now that a simple Shiro environment is set up, let's see what you can do: // 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 om*/ // 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); }