一篇适合小白的Shiro教程

x33g5p2x  于2021-09-19 转载在 其他  
字(68.6k)|赞(0)|评价(0)|浏览(345)

Shiro简介

按照惯例,先上官网https://shiro.apache.org/

什么是Shiro

Shiro是一个功能强大且易于使用的Java安全框架,它执行身份验证、授权、加密和会话管理。使用Shiro易于理解的API,您可以快速轻松地保护任何应用程序—从最小的移动应用程序到最大的web和企业应用程序

Shiro核心架构

Subject

Subject即主体,外部应用与subject进行交互,subject记录了当前的操作用户,将用户的概念理解为当前操作的主体。外部程序通过subject进行认证授权,而subject是通过SecurityManager安全管理器进行认证授权

SecurityManager

SecurityManager即安全管理器,对全部的subject进行安全管理,它是shiro的核心,负责对所有的subject进行安全管理。通过SecurityManager可以完成subject的认证、授权等,实质上SecurityManager是通过Authenticator进行认证,通过Authorizer进行授权,通过SessionManager进行会话管理等

SecurityManager是一个接口,继承了Authenticator, Authorizer, SessionManager这三个接口

Authenticator

Authenticator即认证器,对用户身份进行认证,Authenticator是一个接口,shiro提供ModularRealmAuthenticator实现类,通过ModularRealmAuthenticator基本上可以满足大多数需求,也可以自定义认证器

Authorizer

Authorizer即授权器,用户通过认证器认证通过,在访问功能时需要通过授权器判断用户是否有此功能的操作权限

Realm

Realm即领域,相当于datasource数据源,securityManager进行安全认证需要通过Realm获取用户权限数据,比如:如果用户身份数据在数据库那么realm就需要从数据库获取用户身份信息
不要把realm理解成只是从数据源取数据,在realm中还有认证授权校验的相关的代码

SessionManager

sessionManager即会话管理,shiro框架定义了一套会话管理,它不依赖web容器的session,所以shiro可以使用在非web应用上,也可以将分布式应用的会话集中在一点管理,此特性可使它实现单点登录

SessionDAO

SessionDAO即会话dao,是对session会话操作的一套接口,比如要将session存储到数据库,可以通过jdbc将会话存储到数据库

CacheManager

CacheManager即缓存管理,将用户权限数据存储在缓存,这样可以提高性能

Cryptography

Cryptography即密码管理,shiro提供了一套加密/解密的组件,方便开发。比如提供常用的散列、加/解密等功能。

Shiro中的认证

什么是认证

身份认证,就是判断一个用户是否为合法用户的处理过程。最常用的简单身份认证方式是系统通过核对用户输入的用户名和口令,看其是否与系统中存储的该用户的用户名和口令一致,来判断用户身份是否正确

三个概念

Subject

访问系统的用户,主体可以是用户、程序等,进行认证的都称为主体

Principal

身份信息,是主体(subject)进行身份认证的标识,标识必须具有唯一性,如用户名、手机号、邮箱地址等,一个主体可以有多个身份,但是必须有一个主身份(Primary Principal)

credential

凭证信息,是只有主体自己知道的安全信息,如密码、证书等

认证的实现

创建一个普通的maven项目,引入shiro的pom依赖

  1. <dependency>
  2. <groupId>org.apache.shiro</groupId>
  3. <artifactId>shiro-core</artifactId>
  4. <version>1.5.3</version>
  5. </dependency>

引入shiro配置文件shiro.ini,并加入以下配置

  1. # 约定写法
  2. [users]
  3. # 用户名=密码
  4. christy=123456
  5. tide=654321

shiro的配置文件是一个.ini文件,类似于.txt文件

.ini文件经常用作某些软件的特定的配置文件,可以支持一些复杂的数据格式,shiro可以按照内部约定的某种格式读取配置文件中的数据

之所以提供这个配置文件是用来学习shiro时书写我们系统中相关的权限数据,从而减轻配置数据库并从数据库读取数据的压力,降低学习成本,提高学习效率
1.
测试Java代码

  1. import org.apache.shiro.SecurityUtils;
  2. import org.apache.shiro.authc.AuthenticationToken;
  3. import org.apache.shiro.authc.IncorrectCredentialsException;
  4. import org.apache.shiro.authc.UnknownAccountException;
  5. import org.apache.shiro.authc.UsernamePasswordToken;
  6. import org.apache.shiro.mgt.DefaultSecurityManager;
  7. import org.apache.shiro.realm.text.IniRealm;
  8. import org.apache.shiro.subject.Subject;
  9. public class ShiroAuthenticatorTest {
  10. public static void main(String[] args){
  11. // 1、创建安全管理器对象
  12. DefaultSecurityManager securityManager = new DefaultSecurityManager();
  13. // 2、给安全管理器设置realm
  14. securityManager.setRealm(new IniRealm("classpath:shiro.ini"));
  15. // 3、给全局安全工具类SecurityUtils设置安全管理器
  16. SecurityUtils.setSecurityManager(securityManager);
  17. // 4、拿到当前的subject
  18. Subject subject = SecurityUtils.getSubject();
  19. // 5、创建令牌
  20. AuthenticationToken token = new UsernamePasswordToken("christy","123456");
  21. try {
  22. // 6、用户认证
  23. System.out.println("认证状态:"+subject.isAuthenticated());
  24. subject.login(token);
  25. System.out.println("认证状态:"+subject.isAuthenticated());
  26. } catch (UnknownAccountException e){
  27. e.printStackTrace();
  28. System.out.println("认证失败:用户不存在!");
  29. } catch (IncorrectCredentialsException e){
  30. e.printStackTrace();
  31. System.out.println("认证失败:密码不正确!");
  32. } catch (Exception e){
  33. e.printStackTrace();
  34. }
  35. }
  36. }

认证的几种状态

UnknownAccountException:用户名错误

IncorrectCredentialsException:密码错误

DisabledAccountException:账号被禁用

LockedAccountException:账号被锁定

ExcessiveAttemptsException:登录失败次数过多

ExpiredCredentialsException:凭证过期

Shiro认证的源码分析

上面我们已经简单实现了shiro的认证,但是shiro内部认证的具体流程是怎么样的,这次我们通过追踪源码的方式具体分析一下。我们在认证处打上断点,点击debug模式运行,然后一步步运行到最后,中间经过的类我们都记录下来

至此啊,在SimpleAccountRealm中完成了用户名的认证。

那么密码呢?在哪里校验的呢?我们继续点击下一步,直到这里

我们看到这里断言密码是否匹配的方法,点进去

我们看到了这里拿的是我们输入的密码和根据token取出的用户中的密码做的比较来验证密码是否正确,这是系统帮我们完成的

上面我们说了用户的认证是在SimpleAccountRealmdoGetAuthenticationInfo的方法中完成的,而SimpleAccountRealm继承自AuthorizingRealm,而AuthorizingRealm中有一个抽象方法

  1. protected abstract AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection var1);

SimpleAccountRealm就是复写了AuthorizingRealm中的这个抽象方法实现的用户认证,所以后面我们需要自定义认证的时候我们就可以自定义一个realm继承自AuthorizingRealm来复写doGetAuthorizationInfo,在这个方法里面实现我们自己的认证逻辑

不仅认证,有意思的是AuthorizingRealm是继承自AuthenticatingRealm,而AuthenticatingRealm中有个抽象方法

  1. protected abstract AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken var1) throws AuthenticationException;

这个方法是实现用户授权的方法。

也就是说通过我们自定义realm继承AuthorizingRealm就可以同时复写认证和授权两个方法

Realm的继承关系如下

Shiro使用自定义Relam实现认证

上面我们实现了简单的认证并且分析了认证的基本流程,通常情况下shiro的认证都是通过自定义relam来实现的

CustomerRealm

首先我们编写自定义realm的代码:

  1. import org.apache.shiro.authc.AuthenticationException;
  2. import org.apache.shiro.authc.AuthenticationInfo;
  3. import org.apache.shiro.authc.AuthenticationToken;
  4. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  5. import org.apache.shiro.authz.AuthorizationInfo;
  6. import org.apache.shiro.realm.AuthorizingRealm;
  7. import org.apache.shiro.subject.PrincipalCollection;
  8. /** * 自定义realm */
  9. public class CustomerRealm extends AuthorizingRealm {
  10. // 授权
  11. @Override
  12. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  13. return null;
  14. }
  15. // 认证
  16. @Override
  17. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  18. // 在token中获取用户名
  19. String principal = (String) token.getPrincipal();
  20. System.out.println(principal);
  21. // 模拟根据身份信息从数据库查询
  22. if("christy".equals(principal)){
  23. // 参数说明:用户名 | 密码 | 当前realm的名字
  24. SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(principal,"123456",this.getName());
  25. return simpleAuthenticationInfo;
  26. }
  27. return null;
  28. }
  29. }

CustomerRealmAuthenticatorTest

  1. import com.christy.shiro.realm.CustomerRealm;
  2. import org.apache.shiro.SecurityUtils;
  3. import org.apache.shiro.authc.IncorrectCredentialsException;
  4. import org.apache.shiro.authc.UnknownAccountException;
  5. import org.apache.shiro.authc.UsernamePasswordToken;
  6. import org.apache.shiro.mgt.DefaultSecurityManager;
  7. import org.apache.shiro.subject.Subject;
  8. public class CustomerRealmAuthenticatorTest {
  9. public static void main(String[] args) {
  10. // 创建SecurityManager
  11. DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
  12. // 设置自定义realm
  13. defaultSecurityManager.setRealm(new CustomerRealm());
  14. // 设置安全工具类
  15. SecurityUtils.setSecurityManager(defaultSecurityManager);
  16. // 通过安全工具类获取subject
  17. Subject subject = SecurityUtils.getSubject();
  18. // 创建token
  19. UsernamePasswordToken token = new UsernamePasswordToken("christy", "123456");
  20. try {
  21. // 登录认证
  22. subject.login(token);
  23. System.out.println(subject.isAuthenticated());
  24. } catch (UnknownAccountException e) {
  25. e.printStackTrace();
  26. System.out.println("用户名错误");
  27. } catch (IncorrectCredentialsException e) {
  28. e.printStackTrace();
  29. System.out.println("密码错误");
  30. }
  31. }
  32. }

测试

以上代码编写完成后,我们运行CustomerRealmAuthenticatorTest里面的main方法,执行结果如下

Shiro的加密和随机盐

Shiro中密码的加密策略

实际应用中用户的密码并不是明文存储在数据库中的,而是采用一种加密算法将密码加密后存储在数据库中。Shiro中提供了一整套的加密算法,并且提供了随机盐。shiro使用指定的加密算法将用户密码和随机盐进行加密,并按照指定的散列次数将散列后的密码存储在数据库中。由于随机盐每个用户可以不同,这就极大的提高了密码的安全性。

Shiro中的加密方式

  1. import org.apache.shiro.crypto.hash.Md5Hash;
  2. public class ShiroMD5Test {
  3. public static void main(String[] args){
  4. // MD5加密,无随机盐,无散列
  5. Md5Hash md5Hash01 = new Md5Hash("123456");
  6. System.out.println(md5Hash01.toHex());
  7. // MD5+随机盐加密,无散列
  8. Md5Hash md5Hash02 = new Md5Hash("123456","1q2w3e");
  9. System.out.println(md5Hash02.toHex());
  10. // MD5+随机盐加密+散列1024
  11. Md5Hash md5Hash03 = new Md5Hash("123456","1q2w3e",1024);
  12. System.out.println(md5Hash03.toHex());
  13. }
  14. }

运行结果如下

  1. e10adc3949ba59abbe56e057f20f883e
  2. 9eab7472e164bb8c1b823ae960467f74
  3. 41a4e25bcf1272844e38b19047dd68a0

Shiro中自定义加密Realm

CustomerMD5Realm

  1. import org.apache.shiro.authc.AuthenticationException;
  2. import org.apache.shiro.authc.AuthenticationInfo;
  3. import org.apache.shiro.authc.AuthenticationToken;
  4. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  5. import org.apache.shiro.authz.AuthorizationInfo;
  6. import org.apache.shiro.realm.AuthorizingRealm;
  7. import org.apache.shiro.subject.PrincipalCollection;
  8. import org.apache.shiro.util.ByteSource;
  9. public class CustomerMD5Realm extends AuthorizingRealm {
  10. @Override
  11. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
  12. return null;
  13. }
  14. // 认证
  15. @Override
  16. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  17. // 从token中获取用户名
  18. String principal = (String) token.getPrincipal();
  19. if("christy".equals(principal)){
  20. /** * 用户名 * 加密后的密码 * 随机盐 * 当前realm的名称 */
  21. return new SimpleAuthenticationInfo(principal,
  22. "41a4e25bcf1272844e38b19047dd68a0",
  23. ByteSource.Util.bytes("1q2w3e"),
  24. this.getName());
  25. }
  26. return null;
  27. }
  28. }

CustomerMD5AuthenticatorTest

  1. import com.christy.shiro.realm.CustomerMD5Realm;
  2. import org.apache.shiro.SecurityUtils;
  3. import org.apache.shiro.authc.IncorrectCredentialsException;
  4. import org.apache.shiro.authc.UnknownAccountException;
  5. import org.apache.shiro.authc.UsernamePasswordToken;
  6. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  7. import org.apache.shiro.mgt.DefaultSecurityManager;
  8. import org.apache.shiro.subject.Subject;
  9. public class CustomerMD5AuthenticatorTest {
  10. public static void main(String[] args) {
  11. // 创建SecurityManager
  12. DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
  13. // 设置自定义realm
  14. CustomerMD5Realm realm = new CustomerMD5Realm();
  15. // 为realm设置凭证匹配器
  16. HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
  17. // 设置加密算法
  18. credentialsMatcher.setHashAlgorithmName("md5");
  19. // 设置hash次数
  20. credentialsMatcher.setHashIterations(1024);
  21. realm.setCredentialsMatcher(credentialsMatcher);
  22. defaultSecurityManager.setRealm(realm);
  23. // 设置安全工具类
  24. SecurityUtils.setSecurityManager(defaultSecurityManager);
  25. // 通过安全工具类获取subject
  26. Subject subject = SecurityUtils.getSubject();
  27. // 创建token
  28. UsernamePasswordToken token = new UsernamePasswordToken("christy", "123456");
  29. try {
  30. // 登录认证
  31. subject.login(token);
  32. System.out.println("认证成功");
  33. } catch (UnknownAccountException e) {
  34. e.printStackTrace();
  35. System.out.println("用户名错误");
  36. } catch (IncorrectCredentialsException e) {
  37. e.printStackTrace();
  38. System.out.println("密码错误");
  39. }
  40. }
  41. }

测试

Shiro中的授权

什么是授权

授权可简单理解为who对what(which)进行How操作:

Who,即主体(Subject),主体需要访问系统中的资源。

What,即资源(Resource),如系统菜单、页面、按钮、类方法、系统商品信息等。资源包括资源类型资源实例,比如商品信息为资源类型,类型为t01的商品为资源实例,编号为001的商品信息也属于资源实例。

How,权限/许可(Permission),规定了主体对资源的操作许可,权限离开资源没有意义,如用户查询权限、用户添加权限、某个类方法的调用权限、编号为001用户的修改权限等,通过权限可知主体对哪些资源都有哪些操作许可。

授权方式

基于角色的访问控制

RBAC基于角色的访问控制(Role-Based Access Control)是以角色为中心进行访问控制

  1. if(subject.hasRole("admin")){
  2. //操作什么资源
  3. }

基于资源的访问控制

RBAC基于资源的访问控制(Resource-Based Access Control)是以资源为中心进行访问控制

  1. if(subject.isPermission("user:update:01")){ //资源实例
  2. //对01用户进行修改
  3. }
  4. if(subject.isPermission("user:update:*")){ //资源类型
  5. //对01用户进行修改
  6. }

权限字符串

​ 权限字符串的规则是:资源标识符:操作:资源实例标识符,意思是对哪个资源的哪个实例具有什么操作,“:”是资源/操作/实例的分割符,权限字符串也可以使用/*通配符。

例子:

  • 用户创建权限:user:create,或user:create:/*
  • 用户修改实例001的权限:user:update:001
  • 用户实例001的所有权限:user:/*:001

权限的编码方式

编程式

  1. Subject subject = SecurityUtils.getSubject();
  2. if(subject.hasRole("admin")) {
  3. //有权限
  4. } else {
  5. //无权限
  6. }

注解式

  1. @RequiresRoles("admin")
  2. public void hello() {
  3. //有权限
  4. }

标签式

  1. JSP/GSP 标签:在JSP/GSP 页面通过相应的标签完成:
  2. <shiro:hasRole name="admin">
  3. <!— 有权限—>
  4. </shiro:hasRole>
  5. 注意: Thymeleaf 中使用shiro需要额外集成!

授权的实现

我们基于上面MD5加密的例子进行修改

CustomerMD5Realm

  1. import org.apache.shiro.authc.AuthenticationException;
  2. import org.apache.shiro.authc.AuthenticationInfo;
  3. import org.apache.shiro.authc.AuthenticationToken;
  4. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  5. import org.apache.shiro.authz.AuthorizationInfo;
  6. import org.apache.shiro.realm.AuthorizingRealm;
  7. import org.apache.shiro.subject.PrincipalCollection;
  8. import org.apache.shiro.util.ByteSource;
  9. public class CustomerMD5Realm extends AuthorizingRealm {
  10. @Override
  11. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  12. // 从系统返回的身份信息集合中获取主身份信息(用户名)
  13. String primaryPrincipal = (String) principals.getPrimaryPrincipal();
  14. System.out.println("用户名: "+primaryPrincipal);
  15. //根据用户名获取当前用户的角色信息,以及权限信息
  16. SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
  17. //将数据库中查询角色信息赋值给权限对象
  18. simpleAuthorizationInfo.addRole("admin");
  19. simpleAuthorizationInfo.addRole("user");
  20. //将数据库中查询权限信息赋值个权限对象
  21. simpleAuthorizationInfo.addStringPermission("user:*:01");
  22. simpleAuthorizationInfo.addStringPermission("product:create");
  23. return simpleAuthorizationInfo;
  24. }
  25. // 认证
  26. @Override
  27. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  28. // 从token中获取用户名
  29. String principal = (String) token.getPrincipal();
  30. if("christy".equals(principal)){
  31. /** * 用户名 * 加密后的密码 * 随机盐 * 当前realm的名称 */
  32. return new SimpleAuthenticationInfo(principal,
  33. "41a4e25bcf1272844e38b19047dd68a0",
  34. ByteSource.Util.bytes("1q2w3e"),
  35. this.getName());
  36. }
  37. return null;
  38. }
  39. }

CustomerMD5AuthenticatorTest

  1. import com.christy.shiro.realm.CustomerMD5Realm;
  2. import org.apache.shiro.SecurityUtils;
  3. import org.apache.shiro.authc.IncorrectCredentialsException;
  4. import org.apache.shiro.authc.UnknownAccountException;
  5. import org.apache.shiro.authc.UsernamePasswordToken;
  6. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  7. import org.apache.shiro.mgt.DefaultSecurityManager;
  8. import org.apache.shiro.subject.Subject;
  9. public class CustomerMD5AuthenticatorTest {
  10. public static void main(String[] args) {
  11. // 创建SecurityManager
  12. DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
  13. // 设置自定义realm
  14. CustomerMD5Realm realm = new CustomerMD5Realm();
  15. // 为realm设置凭证匹配器
  16. HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
  17. // 设置加密算法
  18. credentialsMatcher.setHashAlgorithmName("md5");
  19. // 设置hash次数
  20. credentialsMatcher.setHashIterations(1024);
  21. realm.setCredentialsMatcher(credentialsMatcher);
  22. defaultSecurityManager.setRealm(realm);
  23. // 设置安全工具类
  24. SecurityUtils.setSecurityManager(defaultSecurityManager);
  25. // 通过安全工具类获取subject
  26. Subject subject = SecurityUtils.getSubject();
  27. // 创建token
  28. UsernamePasswordToken token = new UsernamePasswordToken("christy", "123456");
  29. try {
  30. // 登录认证
  31. subject.login(token);
  32. System.out.println("认证成功");
  33. } catch (UnknownAccountException e) {
  34. e.printStackTrace();
  35. System.out.println("用户名错误");
  36. } catch (IncorrectCredentialsException e) {
  37. e.printStackTrace();
  38. System.out.println("密码错误");
  39. }
  40. //授权
  41. if(subject.isAuthenticated()){
  42. //基于角色权限控制
  43. System.out.println(subject.hasRole("super"));
  44. //基于多角色权限控制(同时具有)
  45. System.out.println(subject.hasAllRoles(Arrays.asList("admin", "super")));
  46. //是否具有其中一个角色
  47. boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "super", "user"));
  48. for (boolean aBoolean : booleans) {
  49. System.out.println(aBoolean);
  50. }
  51. System.out.println("==============================================");
  52. //基于权限字符串的访问控制 资源标识符:操作:资源类型
  53. System.out.println("权限:"+subject.isPermitted("user:update:01"));
  54. System.out.println("权限:"+subject.isPermitted("product:create:02"));
  55. //分别具有那些权限
  56. boolean[] permitted = subject.isPermitted("user:*:01", "order:*:10");
  57. for (boolean b : permitted) {
  58. System.out.println(b);
  59. }
  60. //同时具有哪些权限
  61. boolean permittedAll = subject.isPermittedAll("user:*:01", "product:create:01");
  62. System.out.println(permittedAll);
  63. }
  64. }
  65. }

测试

  1. 用户名: christy
  2. false
  3. 用户名: christy
  4. 用户名: christy
  5. false
  6. 用户名: christy
  7. 用户名: christy
  8. 用户名: christy
  9. true
  10. false
  11. true
  12. ==============================================
  13. 用户名: christy
  14. 权限:true
  15. 用户名: christy
  16. 权限:true
  17. 用户名: christy
  18. 用户名: christy
  19. true
  20. false
  21. 用户名: christy
  22. 用户名: christy
  23. true

Springboot整合Shiro

springboot基本环境搭建

我们新建一个springboot工程springboot_shiro_jsp,本案例使用jsp作为前端页面展示形式,所以新建的springboot工程需要进行一下配置

pom.xml依赖

在pom文件中我们引入jsp解析的依赖

  1. <!-- 引入jsp依赖 -->
  2. <dependency>
  3. <groupId>org.apache.tomcat.embed</groupId>
  4. <artifactId>tomcat-embed-jasper</artifactId>
  5. </dependency>
  6. <dependency>
  7. <groupId>jstl</groupId>
  8. <artifactId>jstl</artifactId>
  9. <version>1.2</version>
  10. </dependency>

webapp目录

main目录下我们新建一个webapp目录,目录里面新建一个jsp文件index.jsp

  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  6. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  7. <title>index</title>
  8. </head>
  9. <body>
  10. hello world!
  11. </body>
  12. </html>

application.yml配置jsp模板

  1. spring:
  2. # 设置视图模板为jsp
  3. mvc:
  4. view:
  5. prefix: /
  6. suffix: .jsp

Working directory目录

启动

以上配置完毕后,启动我们的项目,输入http://localhost:8888/index.jsp

至此,最基本的springboot集成jsp的环境已经搭建完毕了,后面我们要集成shiro

项目中引入Shiro

pom.xml依赖

  1. <!-- shiro -->
  2. <dependency>
  3. <groupId>org.apache.shiro</groupId>
  4. <artifactId>shiro-spring-boot-starter</artifactId>
  5. <version>1.5.3</version>
  6. </dependency>

自定义Realm

我们知道实际开发中使用shiro时都是使用自定的realm,我们先不管三七二十一,先自定义一个realm,暂时不实现认证和授权

  1. import org.apache.shiro.authc.AuthenticationException;
  2. import org.apache.shiro.authc.AuthenticationInfo;
  3. import org.apache.shiro.authc.AuthenticationToken;
  4. import org.apache.shiro.authz.AuthorizationInfo;
  5. import org.apache.shiro.realm.AuthorizingRealm;
  6. import org.apache.shiro.subject.PrincipalCollection;
  7. /** * 自定义realm */
  8. public class CustomerRealm extends AuthorizingRealm {
  9. // 授权
  10. @Override
  11. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  12. return null;
  13. }
  14. // 认证
  15. @Override
  16. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  17. return null;
  18. }
  19. }

ShiroConfiguration

这个类是Shiro的核心配置类,里面继承了ShiroFilter、SecurityManager和上面的自定义的Realm

  1. import com.christy.shiro.realm.CustomerRealm;
  2. import org.apache.shiro.realm.Realm;
  3. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  4. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. /** * Shiro的核心配置类,用来整合shiro框架 */
  10. @Configuration
  11. public class ShiroConfiguration {
  12. //1.创建shiroFilter //负责拦截所有请求
  13. @Bean
  14. public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
  15. ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  16. //给filter设置安全管理器
  17. shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
  18. //配置系统受限资源
  19. //配置系统公共资源
  20. Map<String,String> map = new HashMap<String,String>();
  21. map.put("/index.jsp","authc");//authc 请求这个资源需要认证和授权
  22. //默认认证界面路径
  23. shiroFilterFactoryBean.setLoginUrl("/login.jsp");
  24. shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
  25. return shiroFilterFactoryBean;
  26. }
  27. //2.创建安全管理器
  28. @Bean
  29. public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
  30. DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
  31. //给安全管理器设置
  32. defaultWebSecurityManager.setRealm(realm);
  33. return defaultWebSecurityManager;
  34. }
  35. //3.创建自定义realm
  36. @Bean
  37. public Realm getRealm(){
  38. CustomerRealm customerRealm = new CustomerRealm();
  39. return customerRealm;
  40. }
  41. }

login.jsp与index.jsp

在上面的ShiroConfiguration类中,我们看到未认证的用户访问受限资源(这里指index.jsp)时会自动跳转到登录页面login.jsp,shiro默认的登录页面也是这个,我们新建一个login.jsp

  1. <%--解决页面乱码--%>
  2. <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
  3. <!doctype html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  8. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  9. <title>index</title>
  10. </head>
  11. <body>
  12. <h1>用户登录</h1>
  13. </body>
  14. </html>

为了与login.jsp区别开来,我们更改index.jsp的内容如下

  1. <%--解决页面乱码--%>
  2. <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
  3. <!doctype html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport"
  8. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  9. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  10. <title>login</title>
  11. </head>
  12. <body>
  13. <h1>系统主页</h1>
  14. <ul>
  15. <li><a href="">用户管理</a></li>
  16. <li><a href="">订单管理</a></li>
  17. </ul>
  18. </body>
  19. </html>

启动

以上工作准备完毕后,我们启动项目再次访问index.jsp,发现页面跳转到登录页面。这就说明我们的项目中成功的引入了Shiro

Shiro中常见过滤器

配置缩写对应的过滤器功能
anonAnonymousFilter指定url可以匿名访问
authcFormAuthenticationFilter指定url需要form表单登录,默认会从请求中获取usernamepassword,rememberMe等参数并尝试登录,如果登录不了就会跳转到loginUrl配置的路径。我们也可以用这个过滤器做默认的登录逻辑,但是一般都是我们自己在控制器写登录逻辑的,自己写的话出错返回的信息都可以定制嘛。
authcBasicBasicHttpAuthenticationFilter指定url需要basic登录
logoutLogoutFilter登出过滤器,配置指定url就可以实现退出功能,非常方便
noSessionCreationNoSessionCreationFilter禁止创建会话
permsPermissionsAuthorizationFilter需要指定权限才能访问
portPortFilter需要指定端口才能访问
restHttpMethodPermissionFilter将http请求方法转化成相应的动词来构造一个权限字符串,这个感觉意义不大,有兴趣自己看源码的注释
rolesRolesAuthorizationFilter需要指定角色才能访问
sslSslFilter需要https请求才能访问
userUserFilter需要已登录或“记住我”的用户才能访问

项目中实现认证和退出

login.jsp中实现登录

既然要实现认证就需要用户有登录操作,此时我们去修改以下login.jsp

  1. <form action="${pageContext.request.contextPath}/user/login" method="post">
  2. 用户名:<input type="text" name="username" > <br/>
  3. 密码 : <input type="text" name="password"> <br>
  4. <input type="submit" value="登录">
  5. </form>

我么看到上面的登录请求的url是user/login,这个时候我们就需要一个控制器UserController了

  1. import org.apache.shiro.SecurityUtils;
  2. import org.apache.shiro.authc.IncorrectCredentialsException;
  3. import org.apache.shiro.authc.UnknownAccountException;
  4. import org.apache.shiro.authc.UsernamePasswordToken;
  5. import org.apache.shiro.subject.Subject;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. @Controller
  9. @RequestMapping("user")
  10. public class UserController {
  11. /** * 用户登录 * @param username * @param password * @return */
  12. @RequestMapping("login")
  13. public String login(String username,String password){
  14. // 获取当前登录用户
  15. Subject subject = SecurityUtils.getSubject();
  16. try {
  17. // 执行登录操作
  18. subject.login(new UsernamePasswordToken(username,password));
  19. // 认证通过后直接跳转到index.jsp
  20. return "redirect:/index.jsp";
  21. } catch (UnknownAccountException e) {
  22. e.printStackTrace();
  23. System.out.println("用户名错误~");
  24. } catch (IncorrectCredentialsException e) {
  25. e.printStackTrace();
  26. System.out.println("密码错误~");
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. // 如果认证失败仍然回到登录页面
  31. return "redirect:/login.jsp";
  32. }
  33. }

index.jsp中实现退出

上面我们说了出了认证还有退出功能也要实现,下面我们在index.jsp中实现

  1. <%--解决页面乱码--%>
  2. <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
  3. <!doctype html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport"
  8. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  9. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  10. <title>index</title>
  11. </head>
  12. <body>
  13. <h1>系统主页</h1>
  14. <a href="${pageContext.request.contextPath}/user/logout">退出用户</a>
  15. <ul>
  16. <li><a href="">用户管理</a></li>
  17. <li><a href="">订单管理</a></li>
  18. </ul>
  19. </body>
  20. </html>

同样的我们需要在UserController中实现退出的操作

  1. @RequestMapping("logout")
  2. public String logout(){
  3. Subject subject = SecurityUtils.getSubject();
  4. subject.logout();
  5. // 退出后仍然会到登录页面
  6. return "redirect:/login.jsp";
  7. }

在CustomerRealm中实现认证

  1. import org.apache.shiro.authc.AuthenticationException;
  2. import org.apache.shiro.authc.AuthenticationInfo;
  3. import org.apache.shiro.authc.AuthenticationToken;
  4. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  5. import org.apache.shiro.authz.AuthorizationInfo;
  6. import org.apache.shiro.realm.AuthorizingRealm;
  7. import org.apache.shiro.subject.PrincipalCollection;
  8. /** * 自定义realm */
  9. public class CustomerRealm extends AuthorizingRealm {
  10. // 授权
  11. @Override
  12. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  13. return null;
  14. }
  15. // 认证
  16. @Override
  17. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  18. // 获取当前登录的主题
  19. String principal = (String) token.getPrincipal();
  20. // 模拟数据库返回的数据
  21. if("christy".equals(principal)){
  22. return new SimpleAuthenticationInfo(principal,"123456",this.getName());
  23. }
  24. return null;
  25. }
  26. }

上面的认证中只要我们输入的用户名是christy,密码123456就可以认证通过进入到主页

ShiroConfiguration

最后还有一步千万不能忘了就是修改ShiroConfiguration

  1. //配置系统受限资源
  2. //配置系统公共资源
  3. Map<String,String> map = new HashMap<String,String>();
  4. map.put("/user/login","anon"); // anon 设置为公共资源,放行要注意anon和authc的顺序
  5. map.put("/index.jsp","authc"); //authc 请求这个资源需要认证和授权
  6. //默认认证界面路径
  7. shiroFilterFactoryBean.setLoginUrl("/login.jsp");
  8. shiroFilterFactoryBean.setFilterChainDefinitionMap(map);

测试

以上操作准备完毕后,我们重启项目后进行测试

MD5、Salt的注册流程

新建register.jsp

  1. <%--解决页面乱码--%>
  2. <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
  3. <!doctype html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport"
  8. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  9. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  10. <title>register</title>
  11. </head>
  12. <body>
  13. <h1>用户注册</h1>
  14. <form action="${pageContext.request.contextPath}/user/register" method="post">
  15. 用户名:<input type="text" name="username" > <br/>
  16. 密码 : <input type="text" name="password"> <br>
  17. <input type="submit" value="立即注册">
  18. </form>
  19. </body>
  20. </html>

新建t_user

  1. DROP TABLE IF EXISTS `t_user`;
  2. create table `t_user` (
  3. `id` int (11),
  4. `username` varchar (32),
  5. `password` varchar (32),
  6. `salt` varchar (32),
  7. `age` int (11),
  8. `email` varchar (32),
  9. `address` varchar (128)
  10. );

修改pom.xml

  1. <!-- mybatis plus -->
  2. <dependency>
  3. <groupId>com.baomidou</groupId>
  4. <artifactId>mybatis-plus-boot-starter</artifactId>
  5. <version>3.4.1</version>
  6. </dependency>
  7. <!-- Druid数据源 -->
  8. <dependency>
  9. <groupId>com.alibaba</groupId>
  10. <artifactId>druid-spring-boot-starter</artifactId>
  11. <version>1.1.10</version>
  12. </dependency>
  13. <!-- Mysql -->
  14. <dependency>
  15. <groupId>mysql</groupId>
  16. <artifactId>mysql-connector-java</artifactId>
  17. <scope>runtime</scope>
  18. </dependency>

修改application.yml

  1. spring:
  2. datasource:
  3. type: com.alibaba.druid.pool.DruidDataSource
  4. druid:
  5. driver-class-name: com.mysql.jdbc.Driver
  6. url: jdbc:mysql://localhost:3306/christy?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC
  7. username: root
  8. password: 123456
  9. # 监控统计拦截的filters
  10. filters: stat,wall,log4j,config
  11. # 配置初始化大小/最小/最大
  12. initial-size: 5
  13. min-idle: 5
  14. max-active: 20
  15. # 获取连接等待超时时间
  16. max-wait: 60000
  17. # 间隔多久进行一次检测,检测需要关闭的空闲连接
  18. time-between-eviction-runs-millis: 60000
  19. # 一个连接在池中最小生存的时间
  20. min-evictable-idle-time-millis: 300000
  21. validation-query: SELECT 'x'
  22. test-while-idle: true
  23. test-on-borrow: false
  24. test-on-return: false
  25. # 打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
  26. pool-prepared-statements: false
  27. max-pool-prepared-statement-per-connection-size: 20
  28. mybatis-plus:
  29. type-aliases-package: com.christy.shiro.model.entity
  30. configuration:
  31. map-underscore-to-camel-case: true

新建User.java

  1. /** * @Author Christy * @DESC * @Date 2020/11/16 15:38 **/
  2. @Data
  3. @NoArgsConstructor
  4. @AllArgsConstructor
  5. @TableName("t_user")
  6. @ApiModel("用户实体类")
  7. public class User implements Serializable {
  8. /** 数据库中设置该字段自增时该注解不能少 **/
  9. @TableId(type = IdType.AUTO)
  10. @ApiModelProperty(name = "id", value = "ID 主键")
  11. private Integer id;
  12. @TableField(fill = FieldFill.INSERT_UPDATE)
  13. @ApiModelProperty(name = "username", value = "用户名")
  14. private String username;
  15. @TableField(fill = FieldFill.INSERT_UPDATE)
  16. @ApiModelProperty(name = "password", value = "密码")
  17. private String password;
  18. @TableField(fill = FieldFill.INSERT)
  19. @ApiModelProperty(name = "salt", value = "盐")
  20. private String salt;
  21. @TableField(fill = FieldFill.INSERT_UPDATE)
  22. @ApiModelProperty(name = "age", value = "年龄")
  23. private Integer age;
  24. @TableField(fill = FieldFill.INSERT_UPDATE)
  25. @ApiModelProperty(name = "email", value = "邮箱")
  26. private String email;
  27. @TableField(fill = FieldFill.INSERT_UPDATE)
  28. @ApiModelProperty(name = "address", value = "地址")
  29. private String address;
  30. }

新建UserMapper.java

  1. package com.christy.shiro.model.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.christy.shiro.model.entity.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5. /** * @Author Christy * @DESC * @Date 2020/11/16 15:49 **/
  6. @Mapper
  7. public interface UserMapper extends BaseMapper<User> {
  8. }

新建UserService.java、UserServiceImpl.java及相关类

UserService.java
  1. import com.christy.shiro.model.entity.User;
  2. public interface UserService {
  3. /** * 用户注册 * @param user */
  4. void register(User user);
  5. }
UserServiceImpl.java
  1. package com.christy.shiro.service.impl;
  2. import com.christy.shiro.constants.ShiroConstant;
  3. import com.christy.shiro.model.entity.User;
  4. import com.christy.shiro.model.mapper.UserMapper;
  5. import com.christy.shiro.service.UserService;
  6. import com.christy.shiro.utils.SaltUtil;
  7. import org.apache.shiro.crypto.hash.Md5Hash;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. @Service
  11. public class UserServiceImpl implements UserService {
  12. @Autowired
  13. private UserMapper userMapper;
  14. @Override
  15. public void register(User user) {
  16. // 生成随机盐
  17. String salt = SaltUtil.getSalt(ShiroConstant.SALT_LENGTH);
  18. // 保存随机盐
  19. user.setSalt(salt);
  20. // 生成密码
  21. Md5Hash password = new Md5Hash(user.getPassword(), salt, ShiroConstant.HASH_ITERATORS);
  22. // 保存密码
  23. user.setPassword(password.toHex());
  24. userMapper.insert(user);
  25. }
  26. }
SaltUtil.java
  1. package com.christy.shiro.utils;
  2. import java.util.Random;
  3. /** * 用户随机盐生成工具类 */
  4. public class SaltUtil {
  5. /** * 生成salt的静态方法 * @param n * @return */
  6. public static String getSalt(int n){
  7. char[] chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890!@#$%^&*()".toCharArray();
  8. StringBuilder sb = new StringBuilder();
  9. for (int i = 0; i < n; i++) {
  10. char aChar = chars[new Random().nextInt(chars.length)];
  11. sb.append(aChar);
  12. }
  13. return sb.toString();
  14. }
  15. }
ShiroConstant.java
  1. package com.christy.shiro.constants;
  2. public class ShiroConstant {
  3. /** 随机盐的位数 **/
  4. public static final int SALT_LENGTH = 8;
  5. /** hash的散列次数 **/
  6. public static final int HASH_ITERATORS = 1024;
  7. }

修改UserController.java

  1. package com.christy.shiro.controller;
  2. import com.christy.shiro.model.entity.User;
  3. import com.christy.shiro.service.UserService;
  4. import org.apache.shiro.SecurityUtils;
  5. import org.apache.shiro.authc.IncorrectCredentialsException;
  6. import org.apache.shiro.authc.UnknownAccountException;
  7. import org.apache.shiro.authc.UsernamePasswordToken;
  8. import org.apache.shiro.subject.Subject;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. @Controller
  13. @RequestMapping("user")
  14. public class UserController {
  15. @Autowired
  16. private UserService userService;
  17. …………省略其他方法…………
  18. /** * 用户注册 * @param user * @return */
  19. @RequestMapping("register")
  20. public String register(User user){
  21. try {
  22. userService.register(user);
  23. return "redirect:/login.jsp";
  24. } catch (Exception e) {
  25. e.printStackTrace();
  26. }
  27. return "redirect:/register.jsp";
  28. }
  29. }

修改ShiroConfiguration.java

最后不要忘记修改ShiroConfiguration.java,将register.jsp/user/register配置成公共的可访问资源

  1. // anon 设置为公共资源,放行要注意anon和authc的顺序
  2. map.put("/user/register","anon");
  3. map.put("/register.jsp","anon");

重启项目测试

可以看到我们注册的用户已经顺利保存到数据库,而且密码是经过加密的

MD5、Salt的认证流程

上面我们完成了基于MD5+Salt的注册流程,保存到数据库的密码都是经过加密处理的,这时候再用最初的简单密码匹配器进行equals方法进行登录显然是不行的了,我们下面来改造一下认证的流程

修改UserService.java、UserServiceImpl.java

UserService.java
  1. package com.christy.shiro.service;
  2. import com.christy.shiro.model.entity.User;
  3. public interface UserService {
  4. ……省略其他方法……
  5. /** * 根据用户名获取用户 */
  6. User findUserByUserName(String userName);
  7. }
UserServiceImpl.java
  1. package com.christy.shiro.service.impl;
  2. import com.christy.shiro.constants.ShiroConstant;
  3. import com.christy.shiro.model.entity.User;
  4. import com.christy.shiro.model.mapper.UserMapper;
  5. import com.christy.shiro.service.UserService;
  6. import com.christy.shiro.utils.SaltUtil;
  7. import org.apache.shiro.crypto.hash.Md5Hash;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10. @Service("userService")
  11. public class UserServiceImpl implements UserService {
  12. ……省略其他方法……
  13. @Override
  14. public User findUserByUserName(String userName) {
  15. return userMapper.findUserByUsername(userName);
  16. }
  17. }

修改CustomerRealm.java及其相关类

CustomerRealm.java
  1. package com.christy.shiro.realm;
  2. import com.christy.shiro.model.entity.User;
  3. import com.christy.shiro.service.UserService;
  4. import com.christy.shiro.utils.ApplicationContextUtil;
  5. import org.apache.shiro.authc.AuthenticationException;
  6. import org.apache.shiro.authc.AuthenticationInfo;
  7. import org.apache.shiro.authc.AuthenticationToken;
  8. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  9. import org.apache.shiro.authz.AuthorizationInfo;
  10. import org.apache.shiro.realm.AuthorizingRealm;
  11. import org.apache.shiro.subject.PrincipalCollection;
  12. import org.apache.shiro.util.ByteSource;
  13. import org.springframework.util.ObjectUtils;
  14. /** * 自定义realm */
  15. public class CustomerRealm extends AuthorizingRealm {
  16. // 授权
  17. @Override
  18. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  19. return null;
  20. }
  21. // 认证
  22. @Override
  23. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
  24. // 获取当前登录的主题
  25. String principal = (String) token.getPrincipal();
  26. // 由于CustomerRealm并没有交由工厂管理,故不能诸如UserService
  27. UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
  28. User user = userService.findUserByUserName(principal);
  29. if(!ObjectUtils.isEmpty(user)){
  30. return new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), new CustomerByteSource(user.getSalt()),this.getName());
  31. }
  32. return null;
  33. }
  34. }
ApplicationContextUtil.java
  1. package com.christy.shiro.utils;
  2. import org.springframework.beans.BeansException;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.context.ApplicationContextAware;
  5. import org.springframework.stereotype.Component;
  6. @Component
  7. public class ApplicationContextUtil implements ApplicationContextAware {
  8. public static ApplicationContext context;
  9. @Override
  10. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
  11. this.context = applicationContext;
  12. }
  13. /** * 根据工厂中的类名获取类实例 */
  14. public static Object getBean(String beanName){
  15. return context.getBean(beanName);
  16. }
  17. }
CustomerByteSource.java
  1. package com.christy.shiro.configuration.shiro.salt;
  2. import org.apache.shiro.codec.Base64;
  3. import org.apache.shiro.codec.CodecSupport;
  4. import org.apache.shiro.codec.Hex;
  5. import org.apache.shiro.util.ByteSource;
  6. import java.io.File;
  7. import java.io.InputStream;
  8. import java.io.Serializable;
  9. import java.util.Arrays;
  10. //自定义salt实现 实现序列化接口
  11. public class CustomerByteSource implements ByteSource, Serializable {
  12. private byte[] bytes;
  13. private String cachedHex;
  14. private String cachedBase64;
  15. public CustomerByteSource() {
  16. }
  17. public CustomerByteSource(byte[] bytes) {
  18. this.bytes = bytes;
  19. }
  20. public CustomerByteSource(char[] chars) {
  21. this.bytes = CodecSupport.toBytes(chars);
  22. }
  23. public CustomerByteSource(String string) {
  24. this.bytes = CodecSupport.toBytes(string);
  25. }
  26. public CustomerByteSource(ByteSource source) {
  27. this.bytes = source.getBytes();
  28. }
  29. public CustomerByteSource(File file) {
  30. this.bytes = (new CustomerByteSource.BytesHelper()).getBytes(file);
  31. }
  32. public CustomerByteSource(InputStream stream) {
  33. this.bytes = (new CustomerByteSource.BytesHelper()).getBytes(stream);
  34. }
  35. public static boolean isCompatible(Object o) {
  36. return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
  37. }
  38. public byte[] getBytes() {
  39. return this.bytes;
  40. }
  41. public boolean isEmpty() {
  42. return this.bytes == null || this.bytes.length == 0;
  43. }
  44. public String toHex() {
  45. if (this.cachedHex == null) {
  46. this.cachedHex = Hex.encodeToString(this.getBytes());
  47. }
  48. return this.cachedHex;
  49. }
  50. public String toBase64() {
  51. if (this.cachedBase64 == null) {
  52. this.cachedBase64 = Base64.encodeToString(this.getBytes());
  53. }
  54. return this.cachedBase64;
  55. }
  56. public String toString() {
  57. return this.toBase64();
  58. }
  59. public int hashCode() {
  60. return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
  61. }
  62. public boolean equals(Object o) {
  63. if (o == this) {
  64. return true;
  65. } else if (o instanceof ByteSource) {
  66. ByteSource bs = (ByteSource) o;
  67. return Arrays.equals(this.getBytes(), bs.getBytes());
  68. } else {
  69. return false;
  70. }
  71. }
  72. private static final class BytesHelper extends CodecSupport {
  73. private BytesHelper() {
  74. }
  75. public byte[] getBytes(File file) {
  76. return this.toBytes(file);
  77. }
  78. public byte[] getBytes(InputStream stream) {
  79. return this.toBytes(stream);
  80. }
  81. }
  82. }

修改ShiroConfiguration.java及其相关类

ShiroConfiguration.java
  1. package com.christy.shiro.configuration;
  2. import com.christy.shiro.constants.ShiroConstant;
  3. import com.christy.shiro.realm.CustomerRealm;
  4. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  5. import org.apache.shiro.authc.credential.Md5CredentialsMatcher;
  6. import org.apache.shiro.realm.Realm;
  7. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  8. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. /** * Shiro的核心配置类,用来整合shiro框架 */
  14. @Configuration
  15. public class ShiroConfiguration {
  16. ……省略其他方法……
  17. //3.创建自定义realm
  18. @Bean
  19. public Realm getRealm(){
  20. CustomerRealm customerRealm = new CustomerRealm();
  21. // 设置密码匹配器
  22. HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
  23. // 设置加密方式
  24. credentialsMatcher.setHashAlgorithmName(ShiroConstant.HASH_ALGORITHM_NAME.MD5);
  25. // 设置散列次数
  26. credentialsMatcher.setHashIterations(ShiroConstant.HASH_ITERATORS);
  27. customerRealm.setCredentialsMatcher(credentialsMatcher);
  28. return customerRealm;
  29. }
  30. }
ShiroConstant.java
  1. package com.christy.shiro.constants;
  2. public class ShiroConstant {
  3. /** 随机盐的位数 **/
  4. public static final int SALT_LENGTH = 8;
  5. /** hash的散列次数 **/
  6. public static final int HASH_ITERATORS = 1024;
  7. /** 加密方式 **/
  8. public interface HASH_ALGORITHM_NAME {
  9. String MD5 = "MD5";
  10. }
  11. }

重启项目进行测试

上面我们注册的两个账号都能正常登录,至此基于MD5+Salt的认证流程告一段落

项目中实现授权

基于角色的授权

持久层
  1. # 用户表上面已经有了:t_user
  2. /*Table structure for table `t_role` */
  3. DROP TABLE IF EXISTS `t_role`;
  4. CREATE TABLE `t_role` (
  5. `id` int(11) NOT NULL AUTO_INCREMENT,
  6. `name` varchar(64) DEFAULT NULL,
  7. PRIMARY KEY (`id`)
  8. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
  9. /*Table structure for table `t_user_role` */
  10. DROP TABLE IF EXISTS `t_user_role`;
  11. CREATE TABLE `t_user_role` (
  12. `id` int(11) NOT NULL AUTO_INCREMENT,
  13. `user_id` int(8) DEFAULT NULL,
  14. `role_id` int(8) DEFAULT NULL,
  15. PRIMARY KEY (`id`)
  16. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;

t_user中的数据是我们通过上面认证注册的用户

t_role角色表中有两种角色adminuser

我们为用户christy赋予了admin的权限,tide赋予了user的权限

视图层index.jsp
  1. <%--解决页面乱码--%>
  2. <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
  3. <%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
  4. <!doctype html>
  5. <html lang="en">
  6. <head>
  7. <meta charset="UTF-8">
  8. <meta name="viewport"
  9. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  10. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  11. <title>index</title>
  12. </head>
  13. <body>
  14. <h1>系统主页</h1>
  15. <a href="${pageContext.request.contextPath}/user/logout">退出用户</a>
  16. <ul>
  17. <%-- admin角色的用户能同时拥有用户管理和订单管理的权限,user角色的用户只拥有订单管理的权限 --%>
  18. <shiro:hasRole name="admin">
  19. <li>
  20. <a href="">用户管理</a>
  21. </li>
  22. </shiro:hasRole>
  23. <shiro:hasAnyRoles name="admin,user">
  24. <li><a href="">订单管理</a></li>
  25. </shiro:hasAnyRoles>
  26. </ul>
  27. </body>
  28. </html>
实体类User.java与Role.java
  1. package com.christy.shiro.model.entity;
  2. import com.baomidou.mybatisplus.annotation.*;
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.NoArgsConstructor;
  8. import java.io.Serializable;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /** * @Author Christy * @DESC * @Date 2020/11/16 15:38 **/
  12. @Data
  13. @NoArgsConstructor
  14. @AllArgsConstructor
  15. @TableName("t_user")
  16. @ApiModel("用户实体类")
  17. public class User implements Serializable {
  18. /** 其他属性省略 **/
  19. @TableField(exist = false)
  20. private List<Role> roles = new ArrayList<>();
  21. }
  1. package com.christy.shiro.model.entity;
  2. import com.baomidou.mybatisplus.annotation.*;
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.NoArgsConstructor;
  8. import java.io.Serializable;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /** * @Author Christy * @DESC * @Date 2020/11/16 15:38 **/
  12. @Data
  13. @NoArgsConstructor
  14. @AllArgsConstructor
  15. @TableName("t_role")
  16. @ApiModel("角色实体类")
  17. public class Role implements Serializable {
  18. /** 数据库中设置该字段自增时该注解不能少 **/
  19. @TableId(type = IdType.AUTO)
  20. @ApiModelProperty(name = "id", value = "ID 主键")
  21. private Integer id;
  22. @TableField(fill = FieldFill.INSERT_UPDATE)
  23. @ApiModelProperty(name = "name", value = "角色名称")
  24. private String name;
  25. }
Mapper层
  1. package com.christy.shiro.model.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.christy.shiro.model.entity.User;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.Select;
  6. /** * @Author Christy * @DESC * @Date 2020/11/16 15:49 **/
  7. @Mapper
  8. public interface UserMapper extends BaseMapper<User> {
  9. /** * 根据用户名查找用户 * @author Christy * @date 2020/11/17 22:19 * @param username * @return com.christy.mplus.model.entity.User */
  10. @Select("SELECT u.id,u.username,u.password,u.salt,u.age,u.email,u.address FROM t_user u WHERE u.username = #{username}")
  11. User findUserByUsername(String username);
  12. }
  1. package com.christy.shiro.model.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.christy.shiro.model.entity.Role;
  4. import org.apache.ibatis.annotations.Mapper;
  5. import org.apache.ibatis.annotations.Select;
  6. import java.util.List;
  7. /** * @Author Christy * @DESC * @Date 2020/11/17 22:40 **/
  8. @Mapper
  9. public interface RoleMapper extends BaseMapper<Role> {
  10. /** * 根据用户id查询用户的角色 * @author Christy * @date 2020/11/17 22:42 * @param userId * @return java.util.List<com.christy.mplus.model.entity.Role> */
  11. @Select("select r.id,r.name from t_role r left join t_user_role ur on ur.role_id = r.id where ur.user_id = #{userId}")
  12. List<Role> getRolesByUserId(Integer userId);
  13. }
Service层

UserService不变,新建RoleService.javaRoleServiceImpl.java

  1. package com.christy.shiro.service;
  2. import com.christy.shiro.model.entity.Role;
  3. import java.util.List;
  4. public interface RoleService {
  5. /** * 根据用户id获取用户的角色集合 * @param userId * @return */
  6. List<Role> getRolesByUserId(Integer userId);
  7. }
  1. package com.christy.shiro.service.impl;
  2. import com.christy.shiro.model.entity.Role;
  3. import com.christy.shiro.model.mapper.RoleMapper;
  4. import com.christy.shiro.service.RoleService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.util.List;
  8. @Service("roleService")
  9. public class RoleServiceImpl implements RoleService {
  10. @Autowired
  11. private RoleMapper roleMapper;
  12. @Override
  13. public List<Role> getRolesByUserId(Integer userId) {
  14. return roleMapper.getRolesByUserId(userId);
  15. }
  16. }
Realm中实现授权
  1. package com.christy.shiro.configuration.shiro.realm;
  2. import com.christy.shiro.configuration.shiro.salt.CustomerByteSource;
  3. import com.christy.shiro.model.entity.Role;
  4. import com.christy.shiro.model.entity.User;
  5. import com.christy.shiro.service.RoleService;
  6. import com.christy.shiro.service.UserService;
  7. import com.christy.shiro.utils.ApplicationContextUtil;
  8. import org.apache.shiro.authc.AuthenticationException;
  9. import org.apache.shiro.authc.AuthenticationInfo;
  10. import org.apache.shiro.authc.AuthenticationToken;
  11. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  12. import org.apache.shiro.authz.AuthorizationInfo;
  13. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  14. import org.apache.shiro.realm.AuthorizingRealm;
  15. import org.apache.shiro.subject.PrincipalCollection;
  16. import org.springframework.util.CollectionUtils;
  17. import org.springframework.util.ObjectUtils;
  18. import java.util.List;
  19. /** * 自定义realm */
  20. public class CustomerRealm extends AuthorizingRealm {
  21. // 授权
  22. @Override
  23. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  24. // 获取主身份信息
  25. String principal = (String) principals.getPrimaryPrincipal();
  26. // 根据主身份信息获取角色信息
  27. UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
  28. User user = userService.findUserByUserName(principal);
  29. RoleService roleService = (RoleService) ApplicationContextUtil.getBean("roleService");
  30. List<Role> roles = roleService.getRolesByUserId(user.getId());
  31. if(!CollectionUtils.isEmpty(roles)){
  32. SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
  33. roles.forEach(role -> {
  34. simpleAuthorizationInfo.addRole(role.getName());
  35. });
  36. return simpleAuthorizationInfo;
  37. }
  38. return null;
  39. }
  40. /** 认证代码省略 **/
  41. }
重启项目测试

上图可以看到admin角色的用户登录系统后能够看到用户管理和订单管理,user角色的用户只能看到订单管理

基于权限的授权

持久层

新增t_permissiont_role_permission

  1. /*Table structure for table `t_permission` */
  2. DROP TABLE IF EXISTS `t_permission`;
  3. CREATE TABLE `t_permission` (
  4. `id` int(11) NOT NULL AUTO_INCREMENT,
  5. `name` varchar(128) DEFAULT NULL,
  6. `url` varchar(255) DEFAULT NULL,
  7. PRIMARY KEY (`id`)
  8. ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
  9. /*Table structure for table `t_role_permission` */
  10. DROP TABLE IF EXISTS `t_role_permission`;
  11. CREATE TABLE `t_role_permission` (
  12. `id` int(11) NOT NULL AUTO_INCREMENT,
  13. `role_id` int(11) DEFAULT NULL,
  14. `permission_id` int(11) DEFAULT NULL,
  15. PRIMARY KEY (`id`)
  16. ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

视图层-index.jsp
  1. <%--解决页面乱码--%>
  2. <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
  3. <%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
  4. <!doctype html>
  5. <html lang="en">
  6. <head>
  7. <meta charset="UTF-8">
  8. <meta name="viewport"
  9. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  10. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  11. <title>index</title>
  12. </head>
  13. <body>
  14. <h1>系统主页</h1>
  15. <a href="${pageContext.request.contextPath}/user/logout">退出用户</a>
  16. <ul>
  17. <%-- admin角色的用户能同时拥有用户管理和订单管理的权限,user角色的用户只拥有订单管理的权限 --%>
  18. <shiro:hasRole name="admin">
  19. <li>
  20. <a href="">用户管理</a>
  21. </li>
  22. </shiro:hasRole>
  23. <%-- admin角色的用户对订单有增删改查的权限,user角色的用户只能查看订单 --%>
  24. <shiro:hasAnyRoles name="admin,user">
  25. <li>
  26. <a href="">订单管理</a>
  27. <ul>
  28. <shiro:hasPermission name="order:add:*">
  29. <li><a href="">新增</a></li>
  30. </shiro:hasPermission>
  31. <shiro:hasPermission name="order:del:*">
  32. <li><a href="">删除</a></li>
  33. </shiro:hasPermission>
  34. <shiro:hasPermission name="order:upd:*">
  35. <li><a href="">修改</a></li>
  36. </shiro:hasPermission>
  37. <shiro:hasPermission name="order:find:*">
  38. <li><a href="">查询</a></li>
  39. </shiro:hasPermission>
  40. </ul>
  41. </li>
  42. </shiro:hasAnyRoles>
  43. </ul>
  44. </body>
  45. </html>
实体类Role.java与Permission.java
  1. package com.christy.shiro.model.entity;
  2. import com.baomidou.mybatisplus.annotation.*;
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.NoArgsConstructor;
  8. import java.io.Serializable;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. /** * @Author Christy * @DESC * @Date 2020/11/16 15:38 **/
  12. @Data
  13. @NoArgsConstructor
  14. @AllArgsConstructor
  15. @TableName("t_role")
  16. @ApiModel("角色实体类")
  17. public class Role implements Serializable {
  18. /** 其他属性字段省略 **/
  19. @TableField(exist = false)
  20. private List<Permission> permissions = new ArrayList<>();
  21. }
  1. package com.christy.shiro.model.entity;
  2. import com.baomidou.mybatisplus.annotation.*;
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import lombok.AllArgsConstructor;
  6. import lombok.Data;
  7. import lombok.NoArgsConstructor;
  8. import java.io.Serializable;
  9. /** * @Author Christy * @DESC * @Date 2020/11/16 15:38 **/
  10. @Data
  11. @NoArgsConstructor
  12. @AllArgsConstructor
  13. @TableName("t_permission")
  14. @ApiModel("权限实体类")
  15. public class Permission implements Serializable {
  16. /** 数据库中设置该字段自增时该注解不能少 **/
  17. @TableId(type = IdType.AUTO)
  18. @ApiModelProperty(name = "id", value = "ID主键")
  19. private Integer id;
  20. @TableField(fill = FieldFill.INSERT_UPDATE)
  21. @ApiModelProperty(name = "name", value = "权限名称")
  22. private String name;
  23. @TableField(fill = FieldFill.INSERT_UPDATE)
  24. @ApiModelProperty(name = "url", value = "权限菜单URL")
  25. private String url;
  26. }
Mapper层
  1. package com.christy.shiro.model.mapper;
  2. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  3. import com.christy.shiro.model.entity.Permission;
  4. import com.christy.shiro.model.entity.Role;
  5. import org.apache.ibatis.annotations.Mapper;
  6. import org.apache.ibatis.annotations.Select;
  7. import java.util.List;
  8. @Mapper
  9. public interface PermissionMapper extends BaseMapper<Permission> {
  10. /** * 根据角色id查询权限 * @author Christy * @date 2020/12/01 22:42 * @param roleId * @return java.util.List<com.christy.mplus.model.entity.Permission> */
  11. @Select("select p.id,p.name,p.url from t_permission p left join t_role_permission rp on rp.permission_id = p.id where rp.role_id = #{roleId}")
  12. List<Permission> getPermissionsByRoleId(Integer roleId);
  13. }
Service层
  1. package com.christy.shiro.service;
  2. import com.christy.shiro.model.entity.Permission;
  3. import java.util.List;
  4. public interface PermissionService {
  5. /** * 根据角色id获取权限集合 * @param roleId * @return */
  6. List<Permission> getPermissionsByRoleId(Integer roleId);
  7. }
  1. package com.christy.shiro.service.impl;
  2. import com.christy.shiro.model.entity.Permission;
  3. import com.christy.shiro.model.mapper.PermissionMapper;
  4. import com.christy.shiro.service.PermissionService;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.stereotype.Service;
  7. import java.util.List;
  8. @Service("permissionService")
  9. public class PermissionServiceImpl implements PermissionService {
  10. @Autowired
  11. private PermissionMapper permissionMapper;
  12. @Override
  13. public List<Permission> getPermissionsByRoleId(Integer roleId) {
  14. return permissionMapper.getPermissionsByRoleId(roleId);
  15. }
  16. }
Realm中实现授权
  1. package com.christy.shiro.configuration.shiro.realm;
  2. import com.christy.shiro.configuration.shiro.salt.CustomerByteSource;
  3. import com.christy.shiro.model.entity.Permission;
  4. import com.christy.shiro.model.entity.Role;
  5. import com.christy.shiro.model.entity.User;
  6. import com.christy.shiro.service.PermissionService;
  7. import com.christy.shiro.service.RoleService;
  8. import com.christy.shiro.service.UserService;
  9. import com.christy.shiro.utils.ApplicationContextUtil;
  10. import org.apache.shiro.authc.AuthenticationException;
  11. import org.apache.shiro.authc.AuthenticationInfo;
  12. import org.apache.shiro.authc.AuthenticationToken;
  13. import org.apache.shiro.authc.SimpleAuthenticationInfo;
  14. import org.apache.shiro.authz.AuthorizationInfo;
  15. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  16. import org.apache.shiro.realm.AuthorizingRealm;
  17. import org.apache.shiro.subject.PrincipalCollection;
  18. import org.springframework.util.CollectionUtils;
  19. import org.springframework.util.ObjectUtils;
  20. import java.util.List;
  21. /** * 自定义realm */
  22. public class CustomerRealm extends AuthorizingRealm {
  23. // 授权
  24. @Override
  25. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  26. // 获取主身份信息
  27. String principal = (String) principals.getPrimaryPrincipal();
  28. // 根据主身份信息获取角色信息
  29. UserService userService = (UserService) ApplicationContextUtil.getBean("userService");
  30. User user = userService.findUserByUserName(principal);
  31. RoleService roleService = (RoleService) ApplicationContextUtil.getBean("roleService");
  32. List<Role> roles = roleService.getRolesByUserId(user.getId());
  33. if(!CollectionUtils.isEmpty(roles)){
  34. SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
  35. roles.forEach(role -> {
  36. simpleAuthorizationInfo.addRole(role.getName());
  37. PermissionService permissionService = (PermissionService) ApplicationContextUtil.getBean("permissionService");
  38. List<Permission> permissions = permissionService.getPermissionsByRoleId(role.getId());
  39. if(!CollectionUtils.isEmpty(permissions)){
  40. permissions.forEach(permission -> {
  41. simpleAuthorizationInfo.addStringPermission(permission.getName());
  42. });
  43. }
  44. });
  45. return simpleAuthorizationInfo;
  46. }
  47. return null;
  48. }
  49. /** 认证代码省略 **/
  50. }
重启项目测试

EhCache实现缓存

shiro提供了缓存管理器,这样在用户第一次认证授权后访问其受限资源的时候就不用每次查询数据库从而达到减轻数据压力的作用,使用shiro的缓存管理器也很简单

修改pom.xml

  1. <!--引入shiro和ehcache-->
  2. <dependency>
  3. <groupId>org.apache.shiro</groupId>
  4. <artifactId>shiro-ehcache</artifactId>
  5. <version>1.5.3</version>
  6. </dependency>

修改ShiroConfiguration.java

  1. package com.christy.shiro.configuration.shiro;
  2. import com.christy.shiro.constants.ShiroConstant;
  3. import com.christy.shiro.configuration.shiro.realm.CustomerRealm;
  4. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  5. import org.apache.shiro.cache.ehcache.EhCacheManager;
  6. import org.apache.shiro.realm.Realm;
  7. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  8. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  9. import org.springframework.context.annotation.Bean;
  10. import org.springframework.context.annotation.Configuration;
  11. import java.util.HashMap;
  12. import java.util.Map;
  13. /** * Shiro的核心配置类,用来整合shiro框架 */
  14. @Configuration
  15. public class ShiroConfiguration {
  16. //1.创建shiroFilter //负责拦截所有请求
  17. @Bean
  18. public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
  19. ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  20. //给filter设置安全管理器
  21. shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
  22. //配置系统资源
  23. Map<String,String> map = new HashMap<String,String>();
  24. // anon 设置为公共资源,放行要注意anon和authc的顺序
  25. map.put("/user/login","anon");
  26. map.put("/user/register","anon");
  27. map.put("/register.jsp","anon");
  28. //authc 请求这个资源需要认证和授权
  29. map.put("/index.jsp","authc");
  30. //默认认证界面路径
  31. shiroFilterFactoryBean.setLoginUrl("/login.jsp");
  32. shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
  33. return shiroFilterFactoryBean;
  34. }
  35. //2.创建安全管理器
  36. @Bean
  37. public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
  38. DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
  39. //给安全管理器设置
  40. defaultWebSecurityManager.setRealm(realm);
  41. return defaultWebSecurityManager;
  42. }
  43. //3.创建自定义realm
  44. @Bean
  45. public Realm getRealm(){
  46. CustomerRealm customerRealm = new CustomerRealm();
  47. // 设置密码匹配器
  48. HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
  49. // 设置加密方式
  50. credentialsMatcher.setHashAlgorithmName(ShiroConstant.HASH_ALGORITHM_NAME.MD5);
  51. // 设置散列次数
  52. credentialsMatcher.setHashIterations(ShiroConstant.HASH_ITERATORS);
  53. customerRealm.setCredentialsMatcher(credentialsMatcher);
  54. // 设置缓存管理器
  55. customerRealm.setCacheManager(new EhCacheManager());
  56. // 开启全局缓存
  57. customerRealm.setCachingEnabled(true);
  58. // 开启认证缓存并指定缓存名称
  59. customerRealm.setAuthenticationCachingEnabled(true);
  60. customerRealm.setAuthenticationCacheName("authenticationCache");
  61. // 开启授权缓存并指定缓存名称
  62. customerRealm.setAuthorizationCachingEnabled(true);
  63. customerRealm.setAuthorizationCacheName("authorizationCache");
  64. return customerRealm;
  65. }
  66. }

这样就将EhCache集成进来了,但是shiro的这个缓存是本地缓存,也就是说当程序宕机重启后仍然需要从数据库加载数据,不能实现分布式缓存的功能。下面我们来集成redis来实现缓存

Springboot集成Redis实现Shiro缓存

修改pom.xml

  1. <!-- 引入redis -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>

修改application.yml

  1. spring:
  2. redis:
  3. host: 127.0.0.1
  4. port: 6379
  5. password: lml123456
  6. database: 0

启动redis服务

RedisCacheManager.java与RedisCache.java

  1. package com.christy.shiro.configuration.shiro.cache;
  2. import org.apache.shiro.cache.Cache;
  3. import org.apache.shiro.cache.CacheException;
  4. import org.apache.shiro.cache.CacheManager;
  5. public class RedisCacheManager implements CacheManager {
  6. @Override
  7. public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
  8. System.out.println("缓存名称: "+cacheName);
  9. return new RedisCache<K,V>(cacheName);
  10. }
  11. }
  1. package com.christy.shiro.configuration.shiro.cache;
  2. import com.christy.shiro.utils.ApplicationContextUtil;
  3. import org.apache.shiro.cache.Cache;
  4. import org.apache.shiro.cache.CacheException;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. import org.springframework.data.redis.serializer.StringRedisSerializer;
  7. import java.util.Collection;
  8. import java.util.Set;
  9. public class RedisCache<K,V> implements Cache<K,V> {
  10. private String cacheName;
  11. public RedisCache() {
  12. }
  13. public RedisCache(String cacheName) {
  14. this.cacheName = cacheName;
  15. }
  16. @Override
  17. public V get(K k) throws CacheException {
  18. System.out.println("获取缓存:"+ k);
  19. return (V) getRedisTemplate().opsForHash().get(this.cacheName,k.toString());
  20. }
  21. @Override
  22. public V put(K k, V v) throws CacheException {
  23. System.out.println("设置缓存key: "+k+" value:"+v);
  24. getRedisTemplate().opsForHash().put(this.cacheName,k.toString(),v);
  25. return null;
  26. }
  27. @Override
  28. public V remove(K k) throws CacheException {
  29. return (V) getRedisTemplate().opsForHash().delete(this.cacheName,k.toString());
  30. }
  31. @Override
  32. public void clear() throws CacheException {
  33. getRedisTemplate().delete(this.cacheName);
  34. }
  35. @Override
  36. public int size() {
  37. return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
  38. }
  39. @Override
  40. public Set<K> keys() {
  41. return getRedisTemplate().opsForHash().keys(this.cacheName);
  42. }
  43. @Override
  44. public Collection<V> values() {
  45. return getRedisTemplate().opsForHash().values(this.cacheName);
  46. }
  47. private RedisTemplate getRedisTemplate(){
  48. RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
  49. redisTemplate.setKeySerializer(new StringRedisSerializer());
  50. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  51. return redisTemplate;
  52. }
  53. }

修改ShiroConfiguration.java

这一步主要修改的就是/*/getRealm()//*方法中设置缓存管理器的代码,由EnCacheManager()换成我们自定义的RedisCacheManager()其他的不用动

  1. package com.christy.shiro.configuration.shiro;
  2. import com.christy.shiro.configuration.shiro.cache.RedisCacheManager;
  3. import com.christy.shiro.constants.ShiroConstant;
  4. import com.christy.shiro.configuration.shiro.realm.CustomerRealm;
  5. import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
  6. import org.apache.shiro.cache.ehcache.EhCacheManager;
  7. import org.apache.shiro.realm.Realm;
  8. import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
  9. import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
  10. import org.springframework.context.annotation.Bean;
  11. import org.springframework.context.annotation.Configuration;
  12. import java.util.HashMap;
  13. import java.util.Map;
  14. /** * Shiro的核心配置类,用来整合shiro框架 */
  15. @Configuration
  16. public class ShiroConfiguration {
  17. //1.创建shiroFilter //负责拦截所有请求
  18. @Bean
  19. public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
  20. ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
  21. //给filter设置安全管理器
  22. shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
  23. //配置系统资源
  24. Map<String,String> map = new HashMap<String,String>();
  25. // anon 设置为公共资源,放行要注意anon和authc的顺序
  26. map.put("/user/login","anon");
  27. map.put("/user/register","anon");
  28. map.put("/register.jsp","anon");
  29. //authc 请求这个资源需要认证和授权
  30. map.put("/index.jsp","authc");
  31. //默认认证界面路径
  32. shiroFilterFactoryBean.setLoginUrl("/login.jsp");
  33. shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
  34. return shiroFilterFactoryBean;
  35. }
  36. //2.创建安全管理器
  37. @Bean
  38. public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm){
  39. DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
  40. //给安全管理器设置
  41. defaultWebSecurityManager.setRealm(realm);
  42. return defaultWebSecurityManager;
  43. }
  44. //3.创建自定义realm
  45. @Bean
  46. public Realm getRealm(){
  47. CustomerRealm customerRealm = new CustomerRealm();
  48. // 设置密码匹配器
  49. HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
  50. // 设置加密方式
  51. credentialsMatcher.setHashAlgorithmName(ShiroConstant.HASH_ALGORITHM_NAME.MD5);
  52. // 设置散列次数
  53. credentialsMatcher.setHashIterations(ShiroConstant.HASH_ITERATORS);
  54. customerRealm.setCredentialsMatcher(credentialsMatcher);
  55. // 设置缓存管理器
  56. /*customerRealm.setCacheManager(new EhCacheManager());*/
  57. customerRealm.setCacheManager(new RedisCacheManager());
  58. // 开启全局缓存
  59. customerRealm.setCachingEnabled(true);
  60. // 开启认证缓存并指定缓存名称
  61. customerRealm.setAuthenticationCachingEnabled(true);
  62. customerRealm.setAuthenticationCacheName("authenticationCache");
  63. // 开启授权缓存并指定缓存名称
  64. customerRealm.setAuthorizationCachingEnabled(true);
  65. customerRealm.setAuthorizationCacheName("authorizationCache");
  66. return customerRealm;
  67. }
  68. }

重启项目测试

上图可以看到我们用户登录以后用户的认证和授权数据已经缓存到redis了,这个时候即使程序重启,redis中的缓存数据也不会删除,除非用户自己退出登录。

集成图片验证码

视图层-login.jsp

  1. <%--解决页面乱码--%>
  2. <%@page contentType="text/html; UTF-8" pageEncoding="UTF-8" isELIgnored="false" %>
  3. <!doctype html>
  4. <html lang="en">
  5. <head>
  6. <meta charset="UTF-8">
  7. <meta name="viewport"
  8. content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  9. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  10. <title>login</title>
  11. </head>
  12. <body>
  13. <h1>用户登录</h1>
  14. <form action="${pageContext.request.contextPath}/user/login" method="post">
  15. 用户名:<input type="text" name="username" > <br/>
  16. 密码 : <input type="text" name="password"> <br>
  17. 验证码: <input type="text" name="verifyCode"><img src="${pageContext.request.contextPath}/user/getImage" alt=""><br>
  18. <input type="submit" value="登录">
  19. </form>
  20. </body>
  21. </html>

工具类-VerifyCodeUtil.java

  1. package com.christy.shiro.utils;
  2. import javax.imageio.ImageIO;
  3. import java.awt.*;
  4. import java.awt.geom.AffineTransform;
  5. import java.awt.image.BufferedImage;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.OutputStream;
  10. import java.util.Arrays;
  11. import java.util.Random;
  12. public class VerifyCodeUtil {
  13. //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
  14. public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
  15. private static Random random = new Random();
  16. /** * 使用系统默认字符源生成验证码 * @param verifySize 验证码长度 * @return */
  17. public static String generateVerifyCode(int verifySize) {
  18. return generateVerifyCode(verifySize, VERIFY_CODES);
  19. }
  20. /** * 使用指定源生成验证码 * @param verifySize 验证码长度 * @param sources 验证码字符源 * @return */
  21. public static String generateVerifyCode(int verifySize, String sources) {
  22. if (sources == null || sources.length() == 0) {
  23. sources = VERIFY_CODES;
  24. }
  25. int codesLen = sources.length();
  26. Random rand = new Random(System.currentTimeMillis());
  27. StringBuilder verifyCode = new StringBuilder(verifySize);
  28. for (int i = 0; i < verifySize; i++) {
  29. verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
  30. }
  31. return verifyCode.toString();
  32. }
  33. /** * 生成随机验证码文件,并返回验证码值 * @param w * @param h * @param outputFile * @param verifySize * @return * @throws IOException */
  34. public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
  35. String verifyCode = generateVerifyCode(verifySize);
  36. outputImage(w, h, outputFile, verifyCode);
  37. return verifyCode;
  38. }
  39. /** * 输出随机验证码图片流,并返回验证码 * @param w * @param h * @param os * @param verifySize * @return * @throws IOException */
  40. public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
  41. String verifyCode = generateVerifyCode(verifySize);
  42. outputImage(w, h, os, verifyCode);
  43. return verifyCode;
  44. }
  45. /** * 生成指定验证码图像文件 * @param w * @param h * @param outputFile * @param code * @throws IOException */
  46. public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
  47. if (outputFile == null) {
  48. return;
  49. }
  50. File dir = outputFile.getParentFile();
  51. if (!dir.exists()) {
  52. dir.mkdirs();
  53. }
  54. try {
  55. outputFile.createNewFile();
  56. FileOutputStream fos = new FileOutputStream(outputFile);
  57. outputImage(w, h, fos, code);
  58. fos.close();
  59. } catch (IOException e) {
  60. throw e;
  61. }
  62. }
  63. /** * 输出指定验证码图片流 * @param w * @param h * @param os * @param code * @throws IOException */
  64. public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
  65. int verifySize = code.length();
  66. BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  67. Random rand = new Random();
  68. Graphics2D g2 = image.createGraphics();
  69. g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  70. Color[] colors = new Color[5];
  71. Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN, Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE, Color.PINK, Color.YELLOW};
  72. float[] fractions = new float[colors.length];
  73. for (int i = 0; i < colors.length; i++) {
  74. colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
  75. fractions[i] = rand.nextFloat();
  76. }
  77. Arrays.sort(fractions);
  78. g2.setColor(Color.GRAY);// 设置边框色
  79. g2.fillRect(0, 0, w, h);
  80. Color c = getRandColor(200, 250);
  81. g2.setColor(c);// 设置背景色
  82. g2.fillRect(0, 2, w, h - 4);
  83. //绘制干扰线
  84. Random random = new Random();
  85. g2.setColor(getRandColor(160, 200));// 设置线条的颜色
  86. for (int i = 0; i < 20; i++) {
  87. int x = random.nextInt(w - 1);
  88. int y = random.nextInt(h - 1);
  89. int xl = random.nextInt(6) + 1;
  90. int yl = random.nextInt(12) + 1;
  91. g2.drawLine(x, y, x + xl + 40, y + yl + 20);
  92. }
  93. // 添加噪点
  94. float yawpRate = 0.05f;// 噪声率
  95. int area = (int) (yawpRate * w * h);
  96. for (int i = 0; i < area; i++) {
  97. int x = random.nextInt(w);
  98. int y = random.nextInt(h);
  99. int rgb = getRandomIntColor();
  100. image.setRGB(x, y, rgb);
  101. }
  102. shear(g2, w, h, c);// 使图片扭曲
  103. g2.setColor(getRandColor(100, 160));
  104. int fontSize = h - 4;
  105. Font font = new Font("Algerian", Font.ITALIC, fontSize);
  106. g2.setFont(font);
  107. char[] chars = code.toCharArray();
  108. for (int i = 0; i < verifySize; i++) {
  109. AffineTransform affine = new AffineTransform();
  110. affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
  111. g2.setTransform(affine);
  112. g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
  113. }
  114. g2.dispose();
  115. ImageIO.write(image, "jpg", os);
  116. }
  117. private static Color getRandColor(int fc, int bc) {
  118. if (fc > 255)
  119. fc = 255;
  120. if (bc > 255)
  121. bc = 255;
  122. int r = fc + random.nextInt(bc - fc);
  123. int g = fc + random.nextInt(bc - fc);
  124. int b = fc + random.nextInt(bc - fc);
  125. return new Color(r, g, b);
  126. }
  127. private static int getRandomIntColor() {
  128. int[] rgb = getRandomRgb();
  129. int color = 0;
  130. for (int c : rgb) {
  131. color = color << 8;
  132. color = color | c;
  133. }
  134. return color;
  135. }
  136. private static int[] getRandomRgb() {
  137. int[] rgb = new int[3];
  138. for (int i = 0; i < 3; i++) {
  139. rgb[i] = random.nextInt(255);
  140. }
  141. return rgb;
  142. }
  143. private static void shear(Graphics g, int w1, int h1, Color color) {
  144. shearX(g, w1, h1, color);
  145. shearY(g, w1, h1, color);
  146. }
  147. private static void shearX(Graphics g, int w1, int h1, Color color) {
  148. int period = random.nextInt(2);
  149. boolean borderGap = true;
  150. int frames = 1;
  151. int phase = random.nextInt(2);
  152. for (int i = 0; i < h1; i++) {
  153. double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
  154. g.copyArea(0, i, w1, 1, (int) d, 0);
  155. if (borderGap) {
  156. g.setColor(color);
  157. g.drawLine((int) d, i, 0, i);
  158. g.drawLine((int) d + w1, i, w1, i);
  159. }
  160. }
  161. }
  162. private static void shearY(Graphics g, int w1, int h1, Color color) {
  163. int period = random.nextInt(40) + 10; // 50;
  164. boolean borderGap = true;
  165. int frames = 20;
  166. int phase = 7;
  167. for (int i = 0; i < w1; i++) {
  168. double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames);
  169. g.copyArea(i, 0, 1, h1, 0, (int) d);
  170. if (borderGap) {
  171. g.setColor(color);
  172. g.drawLine(i, (int) d, i, 0);
  173. g.drawLine(i, (int) d + h1, i, h1);
  174. }
  175. }
  176. }
  177. public static void main(String[] args) throws IOException {
  178. //获取验证码
  179. String s = generateVerifyCode(4);
  180. //将验证码放入图片中
  181. outputImage(260, 60, new File(""), s);
  182. System.out.println(s);
  183. }
  184. }

Controller层

UserController.java中有两处变动,其一是需要一个生成验证码的方法并输出到页面;其二是要修改认证的流程,先进行验证码的校验,验证码校验通过以后才可以进行Shiro的认证

  1. package com.christy.shiro.controller;
  2. import com.christy.shiro.model.entity.User;
  3. import com.christy.shiro.service.UserService;
  4. import com.christy.shiro.utils.VerifyCodeUtil;
  5. import io.swagger.annotations.Api;
  6. import io.swagger.annotations.ApiOperation;
  7. import org.apache.shiro.SecurityUtils;
  8. import org.apache.shiro.authc.IncorrectCredentialsException;
  9. import org.apache.shiro.authc.UnknownAccountException;
  10. import org.apache.shiro.authc.UsernamePasswordToken;
  11. import org.apache.shiro.subject.Subject;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.stereotype.Controller;
  14. import org.springframework.web.bind.annotation.RequestMapping;
  15. import javax.servlet.ServletOutputStream;
  16. import javax.servlet.http.HttpServletResponse;
  17. import javax.servlet.http.HttpSession;
  18. import java.io.IOException;
  19. @Controller
  20. @RequestMapping("user")
  21. @Api(tags = "用户管理Controller")
  22. public class UserController {
  23. @Autowired
  24. private UserService userService;
  25. /** 其他方法省略 **/
  26. /** * 用户登录 * @param username * @param password * @return */
  27. @RequestMapping("login")
  28. public String login(String username,String password, String verifyCode,HttpSession session){
  29. // 校验验证码
  30. String verifyCodes = (String) session.getAttribute("verifyCode");
  31. // 获取当前登录用户
  32. Subject subject = SecurityUtils.getSubject();
  33. try {
  34. if(verifyCodes.equalsIgnoreCase(verifyCode)){
  35. subject.login(new UsernamePasswordToken(username,password));
  36. return "redirect:/index.jsp";
  37. } else {
  38. throw new RuntimeException("验证码错误");
  39. }
  40. } catch (UnknownAccountException e) {
  41. e.printStackTrace();
  42. System.out.println("用户名错误~");
  43. } catch (IncorrectCredentialsException e) {
  44. e.printStackTrace();
  45. System.out.println("密码错误~");
  46. } catch (Exception e) {
  47. e.printStackTrace();
  48. }
  49. return "redirect:/login.jsp";
  50. }
  51. @RequestMapping("getImage")
  52. public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
  53. //生成验证码
  54. String verifyCode = VerifyCodeUtil.generateVerifyCode(4);
  55. //验证码放入session
  56. session.setAttribute("verifyCode",verifyCode);
  57. //验证码存入图片
  58. ServletOutputStream os = response.getOutputStream();
  59. response.setContentType("image/png");
  60. VerifyCodeUtil.outputImage(180,40,os,verifyCode);
  61. }
  62. }

ShiroConfiguration.java

最后一定要记得做,就是将生成验证码的请求URL放行

  1. map.put("/user/getImage","anon");

重启项目测试

上面可以看到不输入验证码或者输错验证码是登录不进去的,到此验证码我们也成功实现了。

相关文章

目录