简介
Shiro 官网:http://shiro.apache.org/
Shiro 可以完成:认证、授权、加密、会话管理、与 Web 集成、缓存等。
新建 maven 项目,加入依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-all</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.15</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> </dependency>
在 resources 目录下新建 shiro.ini 配置文件 users 是用户,roles是角色
[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 'delete' (action) the user (type) with # license plate 'zhangsan' (instance specific id) # goodguy :user 这个用户可以对 zhangsan 进行删除 # user:类型 # delete:行为 # zhangsan:id goodguy = user:delete:zhangsan
日志文件 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=TRACE # Disable verbose logging log4j.logger.org.apache.shiro.util.ThreadContext=WARN log4j.logger.org.apache.shiro.cache.ehcache.EhCache=WARN
演示示例
package com.atguigu.shiro; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.*; import org.apache.shiro.config.IniSecurityManagerFactory; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import org.apache.shiro.util.Factory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Shiro 官方提供的示例,简单的演示如何使用Shiro */ public class Quickstart { private static final transient Logger log = LoggerFactory.getLogger(Quickstart.class); public static void main(String[] args) { Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini"); SecurityManager securityManager = factory.getInstance(); SecurityUtils.setSecurityManager(securityManager); // 调用 SecurityUtils.getSubject() 获取当前的 subject Subject currentUser = SecurityUtils.getSubject(); // 测试使用 session // 获取 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 + "]"); } // 测试当前的用户是否已经被认证,即是否已经登录 // 调用 Subject 的 isAuthenticated() if (!currentUser.isAuthenticated()){ // 把用户名和密码封装成 UsernamePasswordToken 对象 UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa"); // rememberme token.setRememberMe(true); try { // 调用 Subject 的 login 方法,执行登录 currentUser.login(token); } // 若没有指定的账户,则 Shiro 会抛出 UnknownAccountException 异常 catch (UnknownAccountException uae) { log.error("There is no user with username of " + token.getPrincipal()); return; } // 若账户存在,但密码不匹配,则 shiro 会抛出 IncorrectCredentialsException 异常 catch (IncorrectCredentialsException ice) { log.error("Password for account " + token.getPrincipal() + " was incorrect!"); return; } // 用户被锁定的异常 catch (LockedAccountException lae) { log.error("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) { } } // 已经登录 log.info("User [" + currentUser.getPrincipal() + "] logged in successfully."); // 测试是否有某一个角色,调用 Subject 的 hasRole() if (currentUser.hasRole("schwartz")){ log.info("May the Schwartz be with you!"); } else { log.error("Hello, mere mortal."); } // 测试某个用户是不是具备某个行为权限,调用 Subject 的 isPermitted() if (currentUser.isPermitted("lightsaber:weild")) { log.info("You may use a lightsaber ring. Use it wisely."); } else { log.error("Sorry, lightsaber rings are for schwartz masters only."); } // 也是测试用是否具备某一个行为,比上面更具体 // 当前用户可以对 user 类型下的 zhangsan 进行删除操作 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.error("Sorry, you aren't allowed to drive the 'eagle5' winnebago!"); } // 执行退出,调用 Subject 的 logout() 方法 System.out.println("测试 logout 方法,用户是否认证,退出前---->" + currentUser.isAuthenticated()); currentUser.logout(); System.out.println("测试 logout 方法,用户是否认证,退出后---->" + currentUser.isAuthenticated()); System.exit(0); } }