Shiro
1. 什么是Shiro
- Apache Shiro是一个fava的安全(权限)框架。
- Shiro可以非常容易的开发出足够好的应用,其不仅可以用在JavaSE环境,也可以用在JavaEE环境。
- Shiro可以完成,认证,授权,加密,会话管理,Web集成,缓存等。
2. Shiro有哪些功能
- Authentication:身份认证、登录,验证用户是不是拥有相应的身份
- Authorization:授权,即权限验证,验证某个已认证的用户是否拥有某个权限,即判断用户能否进行什么操作,如:验证某个用户是否拥有某个角色,或者细粒度的验证某个用户对某个资源是否具有某个权限
- **Session Manager:**会话管理,即用户登录后就是第一次会话,在没有退出之前,它的所有信息都在会话中;会话可以是普通的JavaSE环境,也可以是Web环境
- Cryptography:加密,保护数据的安全性,如密码加密存储到数据库中,而不是明文存储
- WebSupport:Web支持,可以非常容易的集成到Web环境;
- Caching:缓存,比如用户登录后,其用户信息,拥有的角色、权限不必每次去查,这样可以提高效率
- Concurrency:Shiro支持多线程应用的并发验证,即,如在一个线程中开启另一个线程,能把权限自动的传播过去
- Testing:提供测试支持
- Run As:允许一个用户假装为另一个用户(如果他们允许)的身份进行访问
- Remember Me:记住我,这个是非常常见的功能,即一次登录后,下次再来的话不用登录了
3. Shiro内部架构
4. HelloShiro
-
导入依赖
<!-- configure logging --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.21</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies>
-
配置log4j日志
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
-
配置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
-
QuickStart
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; /** * Simple Quickstart application showing how to use Shiro's API. * * @since 0.9 RC2 */ 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); //获取当前的用户对象 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("通过currentUser得到 [" + value + "]"); } //判断当前的用户是否被认证 if (!currentUser.isAuthenticated()) { //Token:令牌,没获取,随机设置 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? } } //打印身份认证 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(); //退出系统 System.exit(0); } }
大致流程:
//获取当前的用户对象
Subject currentUser = SecurityUtils.getSubject();
//通过当前用户得到session
Session session = currentUser.getSession();
//判断当前的用户是否被认证
if (!currentUser.isAuthenticated());
//打印身份认证
log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
//测试角色
if (currentUser.hasRole("schwartz"));
//测试粗粒度权限
if (currentUser.isPermitted("lightsaber:wield"));
//测试细粒度权限
if (currentUser.isPermitted("winnebago:drive:eagle5"));
//注销
currentUser.logout();
//退出系统
System.exit(0);
5. SpringBoot整合Shiro
-
导入thymeleaf依赖
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> </dependency> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-java8time</artifactId> </dependency>
-
编写Controller、实现跳转到首页index.html
-
导入shiro-spring
<!--shiro整合spring的包--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.1</version> </dependency>
-
编写配置类
package com.kung.config; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ShiroConfig { //3.ShiroFilterBean @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager){ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); //设置安全管理器 bean.setSecurityManager(defaultWebSecurityManager); return bean; } //2.DefaultWebSecurityManager @Bean(name="securityManager") public DefaultWebSecurityManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); //关联realm securityManager.setRealm(userRealm); return securityManager; } //1.创建 realm 对象 @Bean public UserRealm userRealm(){ return new UserRealm(); } }
三个bean各自需要,传参过去,然后@Qualifier指定一下方法名即可指定到它需要的!
-
自定义UserRealm
package com.kung.config; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.subject.PrincipalCollection; //自定义UserRealm public class UserRealm extends AuthorizingRealm { //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { System.out.println("执行了=>授权doGetAuthorizationInfo"); return null; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { System.out.println("执行了=>认证doGetAuthorizationInfo"); return null; } }
6. 登录拦截
-
添加过滤器过滤普通用户
//添加shiro的内置过滤器 /* anno:无需认证即可访问 authc:必须认证才可访问 user:必须拥有 记住我 功能才可访问 perms:拥有对某个资源的权限才可访问 role:拥有某个角色权限才可访问 */ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); Map<String, String> filterMap=new LinkedHashMap<>(); filterMap.put("/user/add","authc"); filterMap.put("/user/update","authc"); //设置登录请求 bean.setLoginUrl("/toLogin"); bean.setFilterChainDefinitionMap(filterMap);
-
登录页面的设计和跳转实现即可
7. 用户认证
-
执行登录
@RequestMapping("/login") public String login(String username,String password,Model model){ //获取当前用户 Subject subject = SecurityUtils.getSubject(); //封装用户登录数据 UsernamePasswordToken token = new UsernamePasswordToken(username,password); try { subject.login(token);//执行登录方法,如果没有异常就ok return "index"; }catch(UnknownAccountException e){ //用户名不存在 model.addAttribute("msg","用户名错误"); return "login"; } catch(IncorrectCredentialsException e){ //密码错误 model.addAttribute("msg","密码错误"); return "login"; } }
-
实现用户认证
在登录执行之后会直接跳转到执行认证,更新执行认证:
//用户名 密码 String name="root"; String password="123456"; UsernamePasswordToken userToken = (UsernamePasswordToken) token; if(!userToken.getUsername().equals(name)){ return null;//抛出异常 UnknowAccountException } //密码认证 shiro做 return new SimpleAuthenticationInfo("",password,"");
8. 整合Mybatis
-
导入依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
-
yaml配置
spring: datasource: username: root password: admin url: jdbc:mysql://localhost:3306/rahiafeng?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.jdbc.Driver
-
properties配置
mybatis.type-aliases-package=com.kuang.pojo mybatis.mapper-locations=classpath:mapper/*.xml
-
UserRealm连接真实数据库
UsernamePasswordToken userToken = (UsernamePasswordToken) token; //连接真实数据库 User user = userService.queryUserByName(userToken.getUsername()); if(user==null){ //没有这个人 return null; } //可以加密 MD5 MD5盐值加密 //密码认证 shiro做 return new SimpleAuthenticationInfo("",user.getPwd(),"");
9. 授权实现
-
先给未授权的拦截
//授权,正常情况下未授权会跳转到未授权页面 filterMap.put("/user/add","perms[user:add]"); //未授权页面 bean.setUnauthorizedUrl("/noauth");
-
添加数据库字段,权限
-
实现不同权限看不同东西
//拿到当前登录对象 Subject subject = SecurityUtils.getSubject(); User currentUser = (User) subject.getPrincipal(); //设置当前用户的权限 info.addStringPermission(currentUser.getPerms()); return new SimpleAuthenticationInfo(user,user.getPwd(),"");
10. 整合thymeleaf
-
导入依赖
<!--shiro和thymeleaf整合--> <dependency> <groupId>com.github.theborakompanioni</groupId> <artifactId>thymeleaf-extras-shiro</artifactId> <version>2.0.0</version> </dependency>
-
配置shiroDialect
//整合ShiroDialect:用来整合shiro和thymeleaf public ShiroDialect getShiroDialect(){ return new ShiroDialect(); }
-
获取登录session以改变登录之后无登录按钮
Subject currentSubject =SecurityUtils.getSubject(); Session session = currentSubject.getSession(); session.setAttribute("loginUser",user); //可以加密 MD5 MD5盐值加密 //密码认证 shiro做 return new SimpleAuthenticationInfo(user,user.getPwd(),"");
-
增加约束并前端修改
<!DOCTYPE html> <html lang="en" xmlns:th="https://www.thymeleaf.org" xmlns:shiro="https://www.thymeleaf.org/thymeleaf-extras-shiro"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>首页</h1> <!--从session中判断值--> <div th:if="${session.loginUser==null}"> <a th:href="@{/toLogin}">登录</a> </div> <p th:text="${msg}"></p> </hr> <div shiro:hasPermission="user:add"> <a th:href="@{/user/add}">add</a> </div> <div shiro:hasPermission="user:update"> <a th:href="@{/user/update}">update</a> </div> </body> </html>