List of usage examples for org.apache.shiro SecurityUtils setSecurityManager
public static void setSecurityManager(SecurityManager securityManager)
From source file:com.aegeus.core.AuthenticationConfiguration.java
License:Apache License
@Bean public WebSecurityManager securityManager() { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(realm()); manager.setCacheManager(new MemoryConstrainedCacheManager()); /**/* www . j a v a 2s . c o m*/ * Set security manager */ SecurityUtils.setSecurityManager(manager); return manager; }
From source file:com.at.shiro.ShiroMain.java
public static void main(String[] args) { // All of realms, users, roles and permissions are defined in shiro.ini. Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); // getInstance() is the sole method of Factory // SecurityUtils are the main class of getting Subject. SecurityUtils.setSecurityManager(securityManager); // statically holding the instance of SecurityManager // get the current user (subject = user) Subject currentUser = SecurityUtils.getSubject(); // shiro session Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); // note that the user has not logged in! String value = (String) session.getAttribute("someKey"); if (value.equals("aValue")) { log.info("Retrieved the correct value! [" + value + "]"); }//w w w.ja v a 2 s. c om // if current user has not logged in. if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); // remember the user across different sessions try { currentUser.login(token); // login with token } catch (UnknownAccountException uae) { log.warn("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { log.warn("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { log.warn("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? log.warn("Unexpected exception.", ae); } } // print their identifying principal (in this case, a username): log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); // check role if (currentUser.hasRole("schwartz")) { log.info("May the Schwartz be with you!"); } else { log.info("Hello, mere mortal."); } // check 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."); } // check permission (instance level) 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!"); } // destroy the authenticated session currentUser.logout(); }
From source file:com.atguigu.shiro.helloworld.Quickstart.java
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. SecurityUtils.getSubject(); Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) // Session /*from www . ja v a 2s . c om*/ // Session: Subject#getSession() 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: // . . // Subject isAuthenticated() if (!currentUser.isAuthenticated()) { // UsernamePasswordToken UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); // rememberme token.setRememberMe(true); try { // . currentUser.login(token); } // , shiro UnknownAccountException . catch (UnknownAccountException uae) { log.info("----> There is no user with username of " + token.getPrincipal()); return; } // , , shiro IncorrectCredentialsException catch (IncorrectCredentialsException ice) { log.info("----> Password for account " + token.getPrincipal() + " was incorrect!"); return; } // LockedAccountException 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: // . Subject hasRole . if (currentUser.hasRole("schwartz")) { log.info("----> May the Schwartz be with you!"); } else { log.info("----> Hello, mere mortal."); return; } //test a typed permission (not instance-level) // . Subject isPermitted() 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("user:delete:zhangsan")) { 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! // . Subject Logout() . System.out.println("---->" + currentUser.isAuthenticated()); currentUser.logout(); System.out.println("---->" + currentUser.isAuthenticated()); System.exit(0); }
From source file:com.atguigu.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: //?Shiro?Subject Subject currentUser = SecurityUtils.getSubject(); // Do some stuff with a Session (no need for a web or EJB container!!!) //Session//from w ww. j ava 2s . c o m 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.caricah.iotracah.core.security.DefaultSecurityHandler.java
License:Apache License
public SecurityManager createSecurityManager(String securityFilePath) throws UnRetriableException { Ini ini = new Ini(); ini.loadFromPath(securityFilePath);/* w w w .jav a 2s .c o m*/ IOTIniSecurityManagerFactory iniSecurityManagerFactory = new IOTIniSecurityManagerFactory(ini, getIotSecurityDatastore(), getDefaultPartitionName()); SecurityManager securityManager = iniSecurityManagerFactory.getInstance(); if (securityManager instanceof IOTSecurityManager) { //configure the security manager. IOTSecurityManager iotSecurityManager = (IOTSecurityManager) securityManager; DefaultSessionManager sessionManager = (DefaultSessionManager) iotSecurityManager.getSessionManager(); SecurityUtils.setSecurityManager(iotSecurityManager); //Assign session dao from the security datastore. sessionManager.setSessionDAO(getIotSecurityDatastore()); sessionManager.setSessionListeners(getSessionListenerList()); sessionManager.setSessionValidationSchedulerEnabled(true); sessionManager.setSessionValidationInterval(1000); return securityManager; } else { throw new UnRetriableException( "Security manager has to be an instance of the default security manager (DefaultSecurityManager). " + securityManager.getClass().getName() + " was used instead."); } }
From source file:com.cerebro.gorgone.boot.SecuritySystem.java
public SecuritySystem() { Ini ini = new Ini(); InputStream shiroIni = VaadinServlet.getCurrent().getServletContext() .getResourceAsStream("/WEB-INF/shiro.ini"); ini.load(shiroIni);/*w w w .j ava2 s.com*/ Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory(ini); org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); }
From source file:com.cerebro.gorgone.landingpage.Login.java
public Login() { InputStream iniFile = VaadinServlet.getCurrent().getServletContext() .getResourceAsStream("/WEB-INF/shiro.ini"); if (iniFile == null) { logger.error("Il file Shiro.ini non esiste"); return;//from ww w .j a va 2 s.c o m } else { logger.info("File Shiro.ini presente"); } Ini ini = new Ini(); ini.load(iniFile); Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory(ini); org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); email.focus(); errorMessage.setVisible(false); this.addComponents(email, password, errorMessage, rememberMe, loginB); loginB.addClickListener((Button.ClickEvent e) -> { logger.info("Tentativo di connessione"); Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(email.getValue(), password.getValue()); token.setRememberMe(rememberMe.getValue()); try { currentUser.login(token); Session session = currentUser.getSession(); User user = new User(); user.loadUser(); //session.setAttribute("User", user); getUI().setContent(new Game()); VaadinService.reinitializeSession(VaadinService.getCurrentRequest()); } catch (Exception ex) { logger.error(ex.toString()); email.setValue(""); password.setValue(""); errorMessage.setVisible(true); } }); }
From source file:com.cerebro.provevaadin.Start.java
public Start() { InputStream iniFile = VaadinServlet.getCurrent().getServletContext() .getResourceAsStream("/WEB-INF/shiro.ini"); if (iniFile == null) { logger.error("Il file Shiro.ini non esiste"); return;//from ww w. j a v a2 s . c o m } else { logger.info("File presente"); } Ini ini = new Ini(); ini.load(iniFile); Factory<SecurityManager> factory = new IniSecurityManagerFactory(ini); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); HorizontalLayout root = new HorizontalLayout(); root.setWidth("800px"); root.setHeight("600px"); this.addComponent(root); this.setComponentAlignment(root, Alignment.MIDDLE_CENTER); FormLayout loginDiv = new FormLayout(); root.addComponent(loginDiv); username.focus(); errorMessage.setVisible(false); loginDiv.addComponents(username, password, rememberMe, login, errorMessage); login.addClickListener((Button.ClickEvent e) -> { logger.info("Pulsante: " + e.toString()); Subject currentUser = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(username.getValue(), password.getValue()); token.setRememberMe(rememberMe.getValue()); try { currentUser.login(token); if (currentUser.hasRole("firsttime")) { logger.info("Configurazione parametri del primo avvio"); getUI().setContent(new FirstTime()); } else { logger.info("Classe di gioco principale"); getUI().setContent(new Game()); VaadinService.reinitializeSession(VaadinService.getCurrentRequest()); } } catch (Exception ex) { logger.error("Errore nel login: " + ex.getMessage()); username.setValue(""); password.setValue(""); errorMessage.setVisible(true); } }); FormLayout signInForm = new FormLayout(); root.addComponent(signInForm); usernameSignIn.focus(); sesso.addItems("Maschio", "Femmina"); signInForm.addComponents(usernameSignIn, passwordSignIn, passwordConf, nome, cognome, sesso, eta, signIn); signIn.addClickListener((Button.ClickEvent event) -> { logger.info("Iscrizione al sito"); User utente = new User(); utente.setEmail(usernameSignIn.getValue()); utente.setPassword(passwordSignIn.getValue()); utente.setNomeUtente(nome.getValue()); utente.setCognomeUtente(cognome.getValue()); utente.setSessoUtente(sesso.getValue().toString()); utente.setDataNascitaUtente(eta.getValue()); SignIn signInWindow = new SignIn(utente); signInWindow.center(); UI.getCurrent().addWindow(signInWindow); }); }
From source file:com.chs.model.AppStart.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); // 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 ww . j a v a 2 s. co 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! System.out.println("User is permmitted ?" + currentUser.isAuthenticated()); currentUser.logout(); System.exit(0); }
From source file:com.comp.pruebaconshiro.ShiroAuthService.java
public ShiroAuthService() { Factory factory = new IniSecurityManagerFactory("./src/main/webapp/WEB-INF/shiro.ini"); SecurityManager securityManager = (SecurityManager) factory.getInstance(); // Make the SecurityManager instance available to the entire application // via static memory: SecurityUtils.setSecurityManager(securityManager); }