1.导入依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.7.1</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.26</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.30</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2.配置log4j.properties
log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m %n # General Apache libraries log4j.logger.org.apache=WARN # Spring log4j.logger.org.springframework=WARN # Default Shiro logging log4j.logger.org.apache.shiro=INFO # Disable verbose logging log4j.logger.org.apache.shiro.util.ThreadContext=WARN log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
3.配置shiro.ini
[users] # user ‘root‘ with password ‘secret‘ and the ‘admin‘ role root = secret, admin # user ‘guest‘ with the password ‘guest‘ and the ‘guest‘ role guest = guest, guest # user ‘presidentskroob‘ with password ‘12345‘ ("That‘s the same combination on # my luggage!!!" ;)), and role ‘president‘ presidentskroob = 12345, president # user ‘darkhelmet‘ with password ‘ludicrousspeed‘ and roles ‘darklord‘ and ‘schwartz‘ darkhelmet = ludicrousspeed, darklord, schwartz # user ‘lonestarr‘ with password ‘vespa‘ and roles ‘goodguy‘ and ‘schwartz‘ lonestarr = vespa, goodguy, schwartz # ----------------------------------------------------------------------------- # Roles with assigned permissions # # Each line conforms to the format defined in the # org.apache.shiro.realm.text.TextConfigurationRealm#setRoleDefinitions JavaDoc # ----------------------------------------------------------------------------- [roles] # ‘admin‘ role has all permissions, indicated by the wildcard ‘*‘ admin = * # The ‘schwartz‘ role can do anything (*) with any lightsaber: schwartz = lightsaber:* # The ‘goodguy‘ role is allowed to ‘drive‘ (action) the winnebago (type) with # license plate ‘eagle5‘ (instance specific id) goodguy = winnebago:drive:eagle5
4.quickstart
public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); public static void main(String[] args) { //死代码 DefaultSecurityManager securityManager = new DefaultSecurityManager(); IniRealm iniRealm = new IniRealm("classpath:shiro.ini"); securityManager.setRealm(iniRealm); SecurityUtils.setSecurityManager(securityManager); //获取当前用户对象 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) { } } 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."); } //检测权限 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."); } //是否有更高的权限 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!"); } //注销 currentUser.logout(); //结束quick System.exit(0); } }