List of usage examples for org.apache.shiro SecurityUtils setSecurityManager
public static void setSecurityManager(SecurityManager securityManager)
From source file:com.cqx.tutorial.Tutorial.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 w w. jav a 2s . 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); }
From source file:com.crud.test.ApacheShiroTest.java
public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("My First Apache Shiro Application"); log.info("My First Apache Shiro Application"); Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject currentUser = SecurityUtils.getSubject(); System.out.println("Current User " + currentUser); Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String str = (String) session.getAttribute("someKey"); if (str.equals("aValue")) { log.info("Retrieved Correct value " + str); System.out.println("Retrieved Correct value " + str); }//from w w w.j a v a2s.c o m // let's login the current user so we can check against roles and permissions: if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("root", "secret"); token.setRememberMe(true); try { currentUser.login(token); } catch (UnknownAccountException uae) { System.out.println("There is no user with username of " + token.getPrincipal()); log.info("There is no user with username of " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) { System.out.println("Password for account " + token.getPrincipal() + " was incorrect!"); log.info("Password for account " + token.getPrincipal() + " was incorrect!"); } catch (LockedAccountException lae) { System.out.println("The account for username " + token.getPrincipal() + " is locked. " + "Please contact your administrator to unlock it."); 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): System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully."); log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); //test a role: if (currentUser.hasRole("schwartz")) { System.out.println("May the Schwartz be with you!"); log.info("May the Schwartz be with you!"); } else { System.out.println("Hello, mere mortal."); log.info("Hello, mere mortal."); } //test a typed permission (not instance-level) if (currentUser.isPermitted("lightsaber:wield")) { System.out.println("You may use a lightsaber ring. Use it wisely."); log.info("You may use a lightsaber ring. Use it wisely."); } else { System.out.println("Sorry, lightsaber rings are for schwartz masters only."); log.info("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); 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.crud.test.ApacheShiroTest2.java
public static void main(String[] args) { Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); Subject currentUser = SecurityUtils.getSubject(); Session session = currentUser.getSession(); session.setAttribute("someKey", "aValue"); String str = (String) session.getAttribute("someKey"); if (str.equals("aValue")) { System.out.println("Retrieved Correct value " + str); }/*from ww w.j ava 2 s. com*/ if (!currentUser.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); token.setRememberMe(true); try { currentUser.login(token); } catch (Exception ae) { System.out.println("Exception " + ae); } } System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully."); //Role if (currentUser.hasRole("schwartz")) { System.out.println("May the Schwartz be with you!"); } else { System.out.println("Hello, mere mortal."); } //permission if (currentUser.isPermitted("lightsaber:wield")) { System.out.println("You may use a lightsaber ring. Use it wisely."); } else { System.out.println("Sorry, lightsaber rings are for schwartz masters only."); } //a (very powerful) Instance Level permission: if (currentUser.isPermitted("winnebago:drive:eagle5")) { System.out.println("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'. " + "Here are the keys - have fun!"); } else { System.out.println("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } //all done - log out! currentUser.logout(); System.exit(0); }
From source file:com.demon.shiro.Tutorial.java
public static void main(String[] args) { logger.info("first apache shiro app."); /*/* w w w .j ava2s . c om*/ * SecurityManager shiro ??SecurityManager */ // 1. IniSecurityManagerFactory ini ? SecurityManager Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:com/demon/shiro/shiro.ini"); // 2. SecurityManager SecurityManager manager = factory.getInstance(); // 3. SecurityManager ??? SecurityUtils.setSecurityManager(manager); // ?? Subject subject = SecurityUtils.getSubject(); /* * Subject????? * ?Subject?????? */ /* * Session shiro ?? HttpSession ????? * HTTP ????? API??? */ // ?session Session session = subject.getSession(); session.setAttribute("key", "testValue"); String value = (String) session.getAttribute("key"); logger.info("value is : {}", value); if (!subject.isAuthenticated()) { UsernamePasswordToken token = new UsernamePasswordToken("root", "secret"); token.setRememberMe(true); try { subject.login(token); } catch (Exception e) { logger.error("login error for this token, username:" + token.getUsername(), e); } } logger.info("User [{}] login success.", subject.getPrincipal()); // if (subject.hasRole("admin")) { logger.info("you have admin role."); } else { logger.info("you don't have admin role"); } // ????? if (subject.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."); } // ???? if (subject.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!"); } subject.logout(); }
From source file:com.esha.dropwizard.stormpath.shiro.StormpathShiroBundle.java
License:Apache License
private void initializeShiro(final StormpathShiroConfiguration config, final Optional<GroupPermissionResolver> groupPermissionResolver, final Optional<GroupRoleResolver> groupRoleResolver) { if (config.isEnabled()) { logger.debug("Stormpath Shiro is enabled"); this.securityManager = buildSecurityManager(config, groupPermissionResolver, groupRoleResolver); SecurityUtils.setSecurityManager(securityManager); } else {/*from w w w . java 2 s. c o m*/ logger.debug("Stormpath Shiro is not enabled"); } }
From source file:com.ethercis.logonservice.security.ServiceSecurityManager.java
License:Apache License
/** * initialize the service<p>/*from w w w . ja v a2s .c o m*/ * Service initialization consists in:<p> * <ul> * <li>loading the policy file</li> * </ul> */ public void doInit(RunTimeSingleton glob, ServiceInfo serviceInfo) throws ServiceManagerException { this.global = (glob == null) ? RunTimeSingleton.instance() : glob; String policyType = get(Constants.POLICY_TYPE_TAG, "DEBUG"); // if (serviceInfo != null && serviceInfo.getParameters().containsKey(Constants.POLICY_TYPE_TAG)) // policyType = (String) serviceInfo.getParameters().get(Constants.POLICY_TYPE_TAG); // else //look in environment or default // policyType = global.getProperty().get(Constants.POLICY_TYPE_TAG, "DEBUG"); switch (policyType) { //Java 1.8 ! case "XML": policyMode = Constants.POLICY_XML; break; case "LDAP": policyMode = Constants.POLICY_LDAP; break; case "JDBC": policyMode = Constants.POLICY_JDBC; break; case "DEBUG": policyMode = Constants.POLICY_DEBUG; break; case "SHIRO": policyMode = Constants.POLICY_SHIRO; //initialize Shiro security manager with the specified policy try { String inipath = (String) serviceInfo.getParameters().get("server.security.shiro.inipath"); if (inipath != null) { inipath = global.getProperty().get("server.security.shiro.inipath", ""); if (inipath.length() == 0) { throw new ServiceManagerException(global, SysErrorCode.INTERNAL_ILLEGALARGUMENT, ME, "No ini path supplied for Shiro configuration, please set server.security.shiro.inipath"); } } Ini configuration = new Ini(); InputStream inputStream = new FileInputStream(inipath); configuration.load(inputStream); Factory<org.apache.shiro.mgt.SecurityManager> factory = new IniSecurityManagerFactory( configuration); org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); } catch (Exception e) { throw new ServiceManagerException(glob, SysErrorCode.RESOURCE_CONFIGURATION, ME, "Could not initialize Shiro framework:" + e); } break; default: throw new IllegalArgumentException("Supplied policy mode is not supported:" + policyType); } AnnotatedMBean.RegisterMBean(serviceId, ServiceSecurityManagerMBean.class, this); }
From source file:com.example.services.LoginService.java
@GET @Path("/login/idUsr/{idUsr}/pass/{pass}") @Produces(MediaType.APPLICATION_JSON)/*from ww w . j a v a 2 s . co m*/ public Response logUser(@PathParam("idUsr") String idUsr, @PathParam("pass") String pass) { JSONObject rta = new JSONObject(); Login usuario = new Login(); usuario.setPassword(pass); usuario.setUsername(idUsr); //1. Load the INI configuration try { File jesus = new File("src/main/webapp/WEB-INF:shiro.ini"); Factory<SecurityManager> factory = new IniSecurityManagerFactory( "src\\main\\webapp\\WEB-INF\\shiro.ini"); //2. Create the SecurityManager SecurityManager securityManager = factory.getInstance(); //3. Make it accessible SecurityUtils.setSecurityManager(securityManager); //1. Acquire submitted principals and credentials: AuthenticationToken token = new UsernamePasswordToken(usuario.getUsername(), usuario.getPassword()); //2. Get the current Subject: Subject currentUser = SecurityUtils.getSubject(); //3. Login: currentUser.login(token); RoleDTO satan = new RoleDTO("administrador"); List<RoleDTO> list = new ArrayList<RoleDTO>(); list.add(satan); if (currentUser.hasRole("examplerole")) { rta.put("userRole", "administrador"); return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(list).build(); //show the Create User button } else if (currentUser.hasRole("invitado")) { rta.put("userRole", "invitado"); return Response.status(200).header("Access-Control-Allow-Origin", "*").entity(rta).build(); } else { return Response.status(403).header("Access-Control-Allow-Origin", "*").entity("error").build(); } } catch (Exception e) { return Response.status(403).header("Access-Control-Allow-Origin", "*").entity("error").build(); } }
From source file:com.freedomotic.security.AuthImpl.java
License:Open Source License
/** * *//* w w w .jav a 2s .c o m*/ @Override public void initBaseRealm() { DefaultSecurityManager securityManager = null; if (!realmInited && config.getBooleanProperty("KEY_SECURITY_ENABLE", true)) { baseRealm.setName(BASE_REALM_NAME); baseRealm.setResourcePath( new File(Info.PATHS.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:com.freedomotic.security.AuthImpl2.java
License:Open Source License
/** * */// w w w .ja v a 2 s .c o m @Override public void initBaseRealm() { DefaultSecurityManager securityManager = null; if (!realmInited && config.getBooleanProperty("KEY_SECURITY_ENABLE", true)) { baseRealm.init(); pluginRealm.init(); securityManager = new DefaultSecurityManager(); //securityManager = injector.getInstance(DefaultSecurityManager.class); realmCollection.add(baseRealm); realmCollection.add(pluginRealm); securityManager.setRealms(realmCollection); SecurityUtils.setSecurityManager(securityManager); realmInited = true; } }
From source file:com.gemstone.gemfire.internal.security.GeodeSecurityUtil.java
License:Apache License
/** * initialize Shiro's Security Manager and Security Utilities *///from ww w.jav a 2 s. c o m public static void initSecurity(Properties securityProps) { if (securityProps == null) { return; } String shiroConfig = securityProps.getProperty(SECURITY_SHIRO_INIT); String securityConfig = securityProps.getProperty(SECURITY_MANAGER); String clientAuthenticatorConfig = securityProps.getProperty(SECURITY_CLIENT_AUTHENTICATOR); String peerAuthenticatorConfig = securityProps.getProperty(SECURITY_PEER_AUTHENTICATOR); if (!StringUtils.isBlank(shiroConfig)) { IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:" + shiroConfig); // we will need to make sure that shiro uses a case sensitive permission resolver Section main = factory.getIni().addSection("main"); main.put("geodePermissionResolver", "com.gemstone.gemfire.internal.security.shiro.GeodePermissionResolver"); if (!main.containsKey("iniRealm.permissionResolver")) { main.put("iniRealm.permissionResolver", "$geodePermissionResolver"); } org.apache.shiro.mgt.SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); isIntegratedSecurity = true; } // only set up shiro realm if user has implemented SecurityManager else if (!StringUtils.isBlank(securityConfig)) { securityManager = getObjectOfTypeFromClassName(securityConfig, SecurityManager.class); securityManager.init(securityProps); Realm realm = new CustomAuthRealm(securityManager); org.apache.shiro.mgt.SecurityManager shiroManager = new DefaultSecurityManager(realm); SecurityUtils.setSecurityManager(shiroManager); isIntegratedSecurity = true; } else if (!StringUtils.isBlank(clientAuthenticatorConfig)) { isClientAuthenticator = true; } else if (!StringUtils.isBlank(peerAuthenticatorConfig)) { isPeerAuthenticator = true; } else { isIntegratedSecurity = false; isClientAuthenticator = false; isPeerAuthenticator = false; } // this initializes the post processor String customPostProcessor = securityProps.getProperty(SECURITY_POST_PROCESSOR); if (!StringUtils.isBlank(customPostProcessor)) { postProcessor = getObjectOfTypeFromClassName(customPostProcessor, PostProcessor.class); postProcessor.init(securityProps); } else { postProcessor = null; } }