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("检索到正确的值! [" + 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("用户不存在 " + token.getPrincipal()); } catch (IncorrectCredentialsException ice) {//密码不正确 log.info("帐户密码" + token.getPrincipal() + " 不正确!"); } catch (LockedAccountException lae) {//被锁定 log.info("用户名的帐户 " + token.getPrincipal() + " is locked. " + "请与管理员联系以解除锁定."); } // ... 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:wield")) {//是否有特定权限 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!"); }