石一歌的Shiro笔记

Shiro

概念

  • 权限管理

    • 基本上涉及到用户参与的系统都要进行权限管理,权限管理属于系统安全的范畴,权限管理实现对用户访问系统的控制,按照安全规则或者安全策略控制用户可以访问而且只能访问自己被授权的资源。
    • 权限管理包括用户身份认证和授权两部分,简称认证授权。对于需要访问控制的资源用户首先经过身份认证,认证通过后用户具有该资源的访问权限方可访问。
  • 身份认证

    • 身份认证,就是判断一个用户是否为合法用户的处理过程。最常用的简单身份认证方式是系统通过核对用户输入的用户名和口令,看其是否与系统中存储的该用户的用户名和口令一致,来判断用户身份是否正确。对于采用指纹等系统,则出示指纹;对于硬件Key等刷卡系统,则需要刷卡。
  • 授权

    • 授权,即访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某些资源没有权限是无法访问的

什么是Shiro

Apache Shiro™ is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications.

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

Shiro是apache旗下一个开源框架,它将软件系统的安全认证相关的功能抽取出来,实现用户身份认证,权限授权、加密、会话管理等功能,组成了一个通用的安全认证框架

核心架构

QQ截图20220603152927

  • Subject

    Subject即主体,外部应用与subject进行交互,subject记录了当前操作用户,将用户的概念理解为当前操作的主体,可能是一个通过浏览器请求的用户,也可能是一个运行的程序。

    Subject在shiro中是一个接口,接口中定义了很多认证授相关的方法,外部程序通过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:凭证信息

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

认证流程

c525acf54f0ed950d6da0b848fba8f7f

开发

  • 依赖
              <dependency>
                    <groupId>org.apache.shiro</groupId>
                    <artifactId>shiro-core</artifactId>
                    <version>1.9.0</version>
                </dependency>
  • shiro.ini

    配置文件:名称随意,以 .ini 结尾,放在 resources 目录下

[users]
shiyige=123456
  • 测试代码
@Slf4j
public class TestAuthenticator {
    public static void main(String[] args) {
        //创建安全管理器
        DefaultSecurityManager securityManager = new DefaultSecurityManager();
        //安全管理器设置realms
        securityManager.setRealm(new IniRealm("classpath:shiro.ini"));
        //安全工具类设置安全管理器
        SecurityUtils.setSecurityManager(securityManager);
        //获取主体
        Subject subject = SecurityUtils.getSubject();
        //创建token
        UsernamePasswordToken token = new UsernamePasswordToken("shiyige", "123456");
        //认证
        try {
            log.info("认证状态" + subject.isAuthenticated());
            subject.login(token);
            log.info("认证状态" + subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            log.error("认证失败,用户名不存在");
        } catch (IncorrectCredentialsException e) {
            log.error("认证失败,密码错误");
        }
    }
}
  • 常见的异常类型

    • DisabledAccountException(帐号被禁用)

    • LockedAccountException(帐号被锁定)

    • ExcessiveAttemptsException(登录失败次数过多)

    • ExpiredCredentialsException(凭证过期)

自定义Realm

  • 认证流程
    • 用户名校验是在 SimpleAccountRealm类 的 doGetAuthenticationInfo 方法
    • 密码校验是在 AuthenticatingRealm类 的 assertCredentialsMatch 方法
  • 结论
    • AuthenticatingRealm类 认证realm doGetAuthenticationInfo
    • AuthorizingRealm类 授权realm doGetAuthorizationInfo

Shiro自带的IniRealm从ini配置文件中读取用户的信息,大部分情况下需要从系统的数据库中读取用户信息,所以需要自定义realm。

  • Realm总实现图

Realm

  • 认证使用的图

Realm

  • 源码
public class SimpleAccountRealm extends AuthorizingRealm {
    ......
	// 认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken)token;
        SimpleAccount account = this.getUser(upToken.getUsername());
        if (account != null) {
            if (account.isLocked()) {
                throw new LockedAccountException("Account [" + account + "] is locked.");
            }

            if (account.isCredentialsExpired()) {
                String msg = "The credentials for account [" + account + "] are expired";
                throw new ExpiredCredentialsException(msg);
            }
        }

        return account;
    }
	// 授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = this.getUsername(principals);
        this.USERS_LOCK.readLock().lock();

        AuthorizationInfo var3;
        try {
            var3 = (AuthorizationInfo)this.users.get(username);
        } finally {
            this.USERS_LOCK.readLock().unlock();
        }

        return var3;
    }
}
  • 自定义Realm

    认证返回值AuthenticationInfo有两个子实现SimpleAuthenticationInfo、SimpleAccount(区别为SimpleAuthenticationInfo不包含授权信息)

    AuthenticationInfo

@Slf4j
public class CustomerRealm extends AuthorizingRealm {
  /***
   *
   * @param principalCollection 
   * @description 授权
   * @author 石一歌
   * @date 2022/6/5 21:22
   * @return org.apache.shiro.authz.AuthorizationInfo
   */
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
    return null;
  }
  /**
   * @param authenticationToken token
   * @description 认证 无需处理认证逻辑,直接返回AuthenticationInfo的子实现SimpleAuthenticationInfo
   * @author 石一歌
   * @date 2022/6/5 21:14
   * @return org.apache.shiro.authc.AuthenticationInfo
   */
  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
      throws AuthenticationException {
    String principal = String.valueOf(authenticationToken.getPrincipal());
    log.info(String.valueOf(principal));
    //该信息由数据库获取
    String username = "shiyige";
    String password = "123456";
    if (username.equals(principal)) {
      // 参数1:返回数据库中正确的用户名
      // 参数2:返回数据库中正确密码
      // 参数3:提供当前realm的名字
      return new SimpleAuthenticationInfo(principal, password, this.getName());
    }
    return null;
  }
}
  • 自定义Realm认证
@Slf4j
public class TestCustomerRealmAuthenticator {
  public static void main(String[] args) {
    DefaultSecurityManager securityManager = new DefaultSecurityManager();
    securityManager.setRealm(new CustomerRealm());
    SecurityUtils.setSecurityManager(securityManager);
    Subject subject = SecurityUtils.getSubject();
    UsernamePasswordToken token = new UsernamePasswordToken("shiyige", "123456");
    try {
      log.info("认证状态" + subject.isAuthenticated());
      subject.login(token);
      log.info("认证状态" + subject.isAuthenticated());
    } catch (UnknownAccountException e) {
      log.error("认证失败,用户名不存在");
    } catch (IncorrectCredentialsException e) {
      log.error("认证失败,密码错误");
    }
  }
}

自定义Realm(MD5+Salt+Hash)

作用:一般用来加密或者签名(校验和)

特点:MD5算法不可逆,内容相同无论执行多少次,md5生成结果始终是一致

网络上提供的MD5在线解密一般是用穷举的方法

生成结果:始终是一个16进制32位长度字符串

在登录流程中使用MD5+Salt加密密码,将加密密文和盐值存储在数据库。通过盐值和散列算法增大黑客的破解成本。

继承的认证域有默认实现的凭证匹配器,使用MD5算法,需要手动调节为hash凭证匹配器。

  • MD5的基本使用
public class TestShiroMD5 {
  public static void main(String[] args) {

    // 使用md5
    Md5Hash md5Hash = new Md5Hash("123456");
    System.out.println(md5Hash.toHex());

    // 使用MD5 + salt处理
    Md5Hash md5Hash1 = new Md5Hash("123456", "@#$*&QU7O0!");
    System.out.println(md5Hash1.toHex());

    // 使用md5 + salt + hash散列(参数代表要散列多少次,一般是 1024或2048)
    Md5Hash md5Hash2 = new Md5Hash("123456", "@#$*&QU7O0!", 1024);
    System.out.println(md5Hash2.toHex());
  }
}
  • 自定义MD5realm
@Slf4j
public class CustomerMd5Realm extends AuthorizingRealm {
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    return null;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {
    String principal = String.valueOf(token.getPrincipal());
    log.info(String.valueOf(principal));
    // 该信息由数据库获取
    String username = "shiyige";
    String password = "44898e645d7265d0b21591903fe8d309";
    if (username.equals(principal)) {
      // 参数1:返回数据库中正确的用户名
      // 参数2:返回数据库中正确密码
      // 参数3:注册时的随机盐
      // 参数4:realm的名字
      return new SimpleAuthenticationInfo(
          principal, password, ByteSource.Util.bytes("@#$*&QU7O0!"), this.getName());
    }
    return null;
  }
}
  • 自定义MD5realm认证
@Slf4j
public class TestCustomerMd5RealmAuthenicator {
  public static void main(String[] args) {
      DefaultSecurityManager securityManager = new DefaultSecurityManager();
      CustomerMd5Realm realm = new CustomerMd5Realm();
      //创建hash凭证匹配器
      HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
      //加密算法
      hashedCredentialsMatcher.setHashAlgorithmName("md5");
      //散列次数
      hashedCredentialsMatcher.setHashIterations(1024);
      //设置hash凭证匹配器
      realm.setCredentialsMatcher(hashedCredentialsMatcher);
      securityManager.setRealm(realm);
      SecurityUtils.setSecurityManager(securityManager);
      Subject subject = SecurityUtils.getSubject();
      UsernamePasswordToken token = new UsernamePasswordToken("shiyige", "123456");
      try {
          subject.login(token);
          log.info("登录成功");
      } catch (UnknownAccountException e) {
          log.error("用户名错误");
      } catch (IncorrectCredentialsException e) {
          log.error("密码错误");
      }
  }
}

shiro授权

授权,即访问控制,控制谁能访问哪些资源。主体进行身份认证后需要分配权限方可访问系统的资源,对于某些资源没有权限是无法访问的。

关键对象

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

  • Who

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

  • What

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

  • How

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

授权流程

2776d1da95d468069505ec23d87fe23e

授权方式

  • 基于角色的访问控制
//RBAC基于角色的访问控制(Role-Based Access Control)是以角色为中心进行访问控制
if(subject.hasRole("admin")){
   //操作什么资源
}
  • 基于资源的访问控制
//RBAC基于资源的访问控制(Resource-Based Access Control)是以资源为中心进行访问控制
if(subject.isPermission("user:update:01")){ //资源实例
  //对资源01 用户具有修改的权限
}
if(subject.isPermission("user:update:*")){  //资源类型
  //对所有的资源 用户具有更新的权限
}

权限字符串

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

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

授权实现方式

  • 编程式
Subject subject = SecurityUtils.getSubject();
if(subject.hasRole("admin")) {
	//有权限
} else {
	//无权限
}
  • 注解式
@RequiresRoles("admin")
public void hello() {
	//有权限
}
  • 标签式
JSP/GSP 标签:在JSP/GSP 页面通过相应的标签完成:
<shiro:hasRole name="admin">
	<!--有权限-->
</shiro:hasRole>
注意: Thymeleaf 中使用shiro需要额外集成!

springboot整合shiro

思路

5c1210afc1af6057213e44b8c1250154

配置

  • pom
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--JSP解析-->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!--shiro-->
        <!--引入shiro整合Springboot依赖-->
        <dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-spring-boot-starter</artifactId>
            <version>1.5.3</version>
        </dependency>
  • application.properties
server.port=8080
server.servlet.context-path=/shiro
spring.application.name=shiro

spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

简单使用

  • ShiroConfig
@Configuration
public class Shiroconfig {
  // 1.创建shiroFilter
  @Bean
  public ShiroFilterFactoryBean getShiroFilterFactoryBean(
      DefaultWebSecurityManager defaultWebSecurityManager) {
    ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
    // 设置安全管理器
    shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
    // 配置系统受限资源
    // 配置系统公共资源
    Map<String, String> map = new HashMap<>();
    // authc 需要认证和授权
    map.put("/user/login", "anon");
    map.put("/**", "authc");
    // 默认认证界面路径
    shiroFilterFactoryBean.setLoginUrl("/login.jsp");
    shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
    return shiroFilterFactoryBean;
  }

  // 创建安全管理器
  @Bean
  public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
    DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
    // 设置自定义realm
    defaultWebSecurityManager.setRealm(realm);
    return defaultWebSecurityManager;
  }

  // 创建自定义realm
  @Bean
  public Realm getRealm() {
    return new CustomRealm();
  }
}
  • CustomRealm
public class CustomRealm extends AuthorizingRealm {
  @Override
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    return null;
  }

  @Override
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
      throws AuthenticationException {
    String principal = (String) token.getPrincipal();
    System.out.println("用户名" + principal);
    String password = "123456";
    String username = "shiyige";
    if (username.equals(principal)) {
      return new SimpleAuthenticationInfo(principal, password, this.getName());
    }
    return null;
  }
}
  • UserController

    @Controller
    @RequestMapping("/user")
    public class UserController {
      @RequestMapping("/login")
      public String login(String username, String password) {
        try {
          Subject subject = SecurityUtils.getSubject();
          subject.login(new UsernamePasswordToken(username, password));
          return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
          e.printStackTrace();
          System.out.println("用户名错误!");
        } catch (IncorrectCredentialsException e) {
          e.printStackTrace();
          System.out.println("密码错误!");
        } catch (Exception e) {
          e.printStackTrace();
          System.out.println(e.getMessage());
        }
        return "redirect:/login.jsp";
      }
    
      @RequestMapping("logout")
      public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
      }
    }
    
  • jsp

    index.jsp

    <%@page contentType="text/html;utf-8" pageEncoding="utf-8" isELIgnored="false" %>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
    <%--    受限资源--%>
    <h1>系统主页</h1>
    <ul>
        <li><a href="#">用户管理</a></li>
        <li><a href="#">商品管理</a></li>
        <li><a href="#">订单管理</a></li>
        <li><a href="#">物流管理</a></li>
    </ul>
    </body>
    </html>
    

    login.jsp

    <%@page contentType="text/html;utf-8" pageEncoding="utf-8" isELIgnored="false" %>
    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
    <%--    受限资源--%>
    <h1>系统主页</h1>
    <a href="${pageContext.request.contextPath}/user/logout">退出登录</a>
    <ul>
        <li><a href="#">用户管理</a></li>
        <li><a href="#">商品管理</a></li>
        <li><a href="#">订单管理</a></li>
        <li><a href="#">物流管理</a></li>
    </ul>
    </body>
    </html>
    
    

常见过滤器

注意: shiro提供和多个默认的过滤器,我们可以用这些过滤器来配置控制指定url的权限

配置缩写 对应的过滤器 功能
anon AnonymousFilter 指定url可以匿名访问(访问时不需要认证授权)
authc FormAuthenticationFilter 指定url需要form表单登录,默认会从请求中获取username、password,rememberMe等参数并尝试登录,如果登录不了就会跳转到loginUrl配置的路径。我们也可以用这个过滤器做默认的登录逻辑,但是一般都是我们自己在控制器写登录逻辑的,自己写的话出错返回的信息都可以定制嘛。
authcBasic BasicHttpAuthenticationFilter 指定url需要basic登录
logout LogoutFilter 登出过滤器,配置指定url就可以实现退出功能,非常方便
noSessionCreation NoSessionCreationFilter 禁止创建会话
perms PermissionsAuthorizationFilter 需要指定权限才能访问
port PortFilter 需要指定端口才能访问
rest HttpMethodPermissionFilter 将http请求方法转化成相应的动词来构造一个权限字符串,这个感觉意义不大,有兴趣自己看源码的注释
roles RolesAuthorizationFilter 需要指定角色才能访问
ssl SslFilter 需要https请求才能访问
user UserFilter 需要已登录或“记住我”的用户才能访问

认证(加盐)

  • 数据库

    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    -- ----------------------------
    -- Table structure for t_user
    -- ----------------------------
    DROP TABLE IF EXISTS `t_user`;
    CREATE TABLE `t_user` (
      `id` int(6) NOT NULL AUTO_INCREMENT,
      `username` varchar(40) DEFAULT NULL,
      `password` varchar(40) DEFAULT NULL,
      `salt` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    
    SET FOREIGN_KEY_CHECKS = 1;
    
  • 依赖

            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.1.2</version>
            </dependency>
            <!--mysql-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.29</version>
            </dependency>
            <!--druid-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.19</version>
            </dependency>
    
  • 配置

    mybatis:
      mapper-locations: classpath:mapper/*.xml
      type-aliases-package: com.nuc.springboot_jsp_shiro.pojo
    server:
      port: 8080
      servlet:
        context-path: /shiro
    spring:
      application:
        name: shiro
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: root
        type: com.alibaba.druid.pool.DruidDataSource
        url: jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true&useSSL=false&serverTimezone=GMT%2b8
        username: root
      mvc:
        view:
          prefix: /
          suffix: .jsp
    
  • UserDao.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.nuc.springboot_jsp_shiro.dao.UserDao">
    
        <insert id="save" parameterType="User" useGeneratedKeys="true" keyProperty="id">
            insert into t_user
            values (#{id}, #{username}, #{password}, #{salt})
        </insert>
        <select id="findByUsername" parameterType="String" resultType="User">
            select id, username, password, salt
            from t_user
            where username = #{username}</select>
    
    </mapper>
    
  • UserDao

    @Mapper
    public interface UserDao {
      void save(User user);
    
      User findByUsername(String username);
    }
    
  • UserService

    public interface UserService {
      void register(User user);
    
      User findByUsername(String username);
    }
    
  • UserServiceImpl

    @Service("userService")
    @Transactional
    public class UserServiceImpl implements UserService {
    
      @Resource private UserDao userDAO;
    
      @Override
      public void register(User user) {
        // 处理业务调用dao
        // 1.生成随机盐
        String salt = SaltUtils.getSalt(8);
        // 2.将随机盐保存到数据
        user.setSalt(salt);
        // 3.明文密码进行md5 + salt + hash散列
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        user.setPassword(md5Hash.toHex());
    
        userDAO.save(user);
      }
    
      @Override
      public User findByUsername(String username) {
        return userDAO.findByUsername(username);
      }
    }
    
  • UserController

    @Controller
    @RequestMapping("/user")
    public class UserController {
      @Resource
      private UserService userService;
    
      @RequestMapping("register")
      public String register(User user) {
        try {
          userService.register(user);
          return "redirect:/login.jsp";
        } catch (Exception e) {
          e.printStackTrace();
          return "redirect:/register.jsp";
        }
      }
    
      @RequestMapping("/login")
      public String login(String username, String password) {
        try {
          Subject subject = SecurityUtils.getSubject();
          subject.login(new UsernamePasswordToken(username, password));
          return "redirect:/index.jsp";
        } catch (UnknownAccountException e) {
          e.printStackTrace();
          System.out.println("用户名错误!");
        } catch (IncorrectCredentialsException e) {
          e.printStackTrace();
          System.out.println("密码错误!");
        } catch (Exception e) {
          e.printStackTrace();
          System.out.println(e.getMessage());
        }
        return "redirect:/login.jsp";
      }
    
      @RequestMapping("logout")
      public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login.jsp";
      }
    }
    
  • ShiroConfig

    @Configuration
    public class Shiroconfig {
      // 1.创建shiroFilter
      @Bean
      public ShiroFilterFactoryBean getShiroFilterFactoryBean(
          DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 配置系统受限资源
        // 配置系统公共资源
        Map<String, String> map = new HashMap<>();
        // authc 需要认证和授权
        map.put("/user/**", "anon");
        map.put("/register.jsp", "anon");
        map.put("/**", "authc");
        // 默认认证界面路径
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
      }
    
      // 创建安全管理器
      @Bean
      public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        // 设置自定义realm
        defaultWebSecurityManager.setRealm(realm);
        return defaultWebSecurityManager;
      }
    
      // 创建自定义realm
      @Bean
      public Realm getRealm() {
    
        CustomRealm customRealm = new CustomRealm();
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024);
        customRealm.setCredentialsMatcher(credentialsMatcher);
        return customRealm;
      }
    }
    
  • CustomRealm

    public class CustomRealm extends AuthorizingRealm {
      @Resource private UserService userService;
    
      @Override
      protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
      }
    
      @Override
      protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
          throws AuthenticationException {
        User user = userService.findByUsername((String) token.getPrincipal());
        if (!ObjectUtils.isEmpty(user)) {
          return new SimpleAuthenticationInfo(
              user.getUsername(),
              user.getPassword(),
              ByteSource.Util.bytes(user.getSalt()),
              this.getName());
        }
        return null;
      }
    }
    
  • SaltUtils

    public class SaltUtils {
      public static String getSalt(int n) {
        char[] chars =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890!@#$%^&*()".toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < n; i++) {
          char aChar = chars[new Random().nextInt(chars.length)];
          sb.append(aChar);
        }
        return sb.toString();
      }
    }
    

授权

image-20200527204839080

  • sql

    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for t_perms
    -- ----------------------------
    DROP TABLE IF EXISTS `t_perms`;
    CREATE TABLE `t_pers` (
      `id` int(6) NOT NULL AUTO_INCREMENT,
      `name` varchar(80) DEFAULT NULL,
      `url` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Table structure for t_role
    -- ----------------------------
    DROP TABLE IF EXISTS `t_role`;
    CREATE TABLE `t_role` (
      `id` int(6) NOT NULL AUTO_INCREMENT,
      `name` varchar(60) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Table structure for t_role_perms
    -- ----------------------------
    DROP TABLE IF EXISTS `t_role_perms`;
    CREATE TABLE `t_role_perms` (
      `id` int(6) NOT NULL,
      `roleid` int(6) DEFAULT NULL,
      `permsid` int(6) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Table structure for t_user
    -- ----------------------------
    DROP TABLE IF EXISTS `t_user`;
    CREATE TABLE `t_user` (
      `id` int(6) NOT NULL AUTO_INCREMENT,
      `username` varchar(40) DEFAULT NULL,
      `password` varchar(40) DEFAULT NULL,
      `salt` varchar(255) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Table structure for t_user_role
    -- ----------------------------
    DROP TABLE IF EXISTS `t_user_role`;
    CREATE TABLE `t_user_role` (
      `id` int(6) NOT NULL,
      `userid` int(6) DEFAULT NULL,
      `roleid` int(6) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    SET FOREIGN_KEY_CHECKS = 1;
    
  • 实体类

    • Role

      @Data
      @Builder
      @AllArgsConstructor
      @NoArgsConstructor
      public class Role {
          private String id;
          private String name;
      }
      
    • Perms

      @Data
      @Builder
      @AllArgsConstructor
      @NoArgsConstructor
      public class Perms {
          private String id;
          private String name;
          private String url;
      }
      
  • Dao

        List<Role> findRolesByUserName(String username);
    
        List<Perms> findPermsByRoleId(String id);
    
  • Mapper

        <select id="findRolesByUserName" parameterType="String" resultType="Role">
            SELECT r.id, r.NAME
            FROM t_user u
                     LEFT JOIN t_user_role ur
                               ON u.id = ur.userid
                     LEFT JOIN t_role r
                               ON ur.roleid = r.id
            WHERE u.username = #{username}
        </select>
    
        <select id="findPermsByRoleId" parameterType="String" resultType="Perms">
            SELECT p.id, p.NAME, p.url
            FROM t_role r
                     LEFT JOIN t_role_perms rp
                               ON r.id = rp.roleid
                     LEFT JOIN t_perms p ON rp.permsid = p.id
            WHERE r.id = #{id}
        </select>
    
  • Service

        List<Role> findRolesByUserName(String username);
    
        List<Perms> findPermsByRoleId(String id);
    
  • ServiceImpl

        @Override
        public List<Perms> findPermsByRoleId(String id) {
            return userDAO.findPermsByRoleId(id);
        }
    
        @Override
        public List<Role> findRolesByUserName(String username) {
            return userDAO.findRolesByUserName(username);
        }
    
  • CustomRealm

    public class CustomRealm extends AuthorizingRealm {
        @Resource
        private UserService userService;
    
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            String principal = (String) principals.getPrimaryPrincipal();
            List<Role> roles = userService.findRolesByUserName(principal);
            if (!CollectionUtils.isEmpty(roles)) {
                SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                roles.forEach(role -> {
                    info.addRole(role.getName());
                    List<Perms> perms = userService.findPermsByRoleId(role.getId());
                    if (!CollectionUtils.isEmpty(perms) && perms.get(0) != null) {
                        perms.forEach(perm -> {
                            info.addStringPermission(perm.getName());
                        });
                    }
                });
                return info;
            }
            return null;
        }
    
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
                throws AuthenticationException {
            User user = userService.findByUsername((String) token.getPrincipal());
            if (!ObjectUtils.isEmpty(user)) {
                return new SimpleAuthenticationInfo(
                        user.getUsername(),
                        user.getPassword(),
                        ByteSource.Util.bytes(user.getSalt()),
                        this.getName());
            }
            return null;
        }
    }
    

QQ截图20220102191802

springboot整合shiro+jwt

简单使用

  • pom

    		<dependency>
                <groupId>com.auth0</groupId>
                <artifactId>java-jwt</artifactId>
                <version>3.4.0</version>
            </dependency>
    
  • LoginController

    验证账号密码无误,会返回Token,其他请求需要携带Token访问

    	@PostMapping("/login")
        public ResultMap login(@RequestParam("username") String username,
                               @RequestParam("password") String password) {
            String realPassword = userMapper.getPassword(username);
            if (realPassword == null) {
                return resultMap.fail().code(401).message("用户名错误");
            } else if (!realPassword.equals(password)) {
                return resultMap.fail().code(401).message("密码错误");
            } else {
                return resultMap.success().code(200).message(JWTUtil.createToken(username));
            }
        }
    
  • JWTUtil

    创建jwt工具类,方便使用,包括生成token验证token以及获取token信息方法

    public class JWTUtil {
        // 过期时间 24 小时
        private static final long EXPIRE_TIME = 60 * 24 * 60 * 1000;
        // 密钥
        private static final String SECRET = "SHIRO+JWT";
    
        /**
         * 生成 token
         *
         * @param username 用户名
         * @return 加密的token
         */
        public static String createToken(String username) {
            try {
                Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
                Algorithm algorithm = Algorithm.HMAC256(SECRET);
                // 附带username信息
                return JWT.create()
                        .withClaim("username", username)
                        //到期时间
                        .withExpiresAt(date)
                        //创建一个新的JWT,并使用给定的算法进行标记
                        .sign(algorithm);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }
    
        /**
         * 校验 token 是否正确
         *
         * @param token    密钥
         * @param username 用户名
         * @return 是否正确
         */
        public static boolean verify(String token, String username) {
            try {
                Algorithm algorithm = Algorithm.HMAC256(SECRET);
                //在token中附带了username信息
                JWTVerifier verifier = JWT.require(algorithm)
                        .withClaim("username", username)
                        .build();
                //验证 token
                verifier.verify(token);
                return true;
            } catch (Exception exception) {
                return false;
            }
        }
    
        /**
         * 获得token中的信息,无需secret解密也能获得
         *
         * @return token中包含的用户名
         */
        public static String getUsername(String token) {
            try {
                DecodedJWT jwt = JWT.decode(token);
                return jwt.getClaim("username").asString();
            } catch (JWTDecodeException e) {
                return null;
            }
        }
    }
    
  • JWTFilter

    自定义过滤器

    检验请求头是否带有 token ((HttpServletRequest) request).getHeader("Token") != null

    如果带有 token,执行 shiro 的 login() 方法,将 token 提交到 Realm 中进行检验;如果没有 token,说明当前状态为游客状态

    如果在 token 校验的过程中出现错误,则重定向到 /unauthorized/**

    public class JWTFilter extends BasicHttpAuthenticationFilter {
        private Logger logger = LoggerFactory.getLogger(this.getClass());
    
        /**
         * 如果带有 token,则对 token 进行检查,否则直接通过
         */
        @Override
        protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws UnauthorizedException {
            //判断请求的请求头是否带上 "Token"
            if (isLoginAttempt(request, response)) {
                //如果存在,则进入 executeLogin 方法执行登入,检查 token 是否正确
                try {
                    executeLogin(request, response);
                    return true;
                } catch (Exception e) {
                    //token 错误
                    responseError(response, e.getMessage());
                }
            }
            //如果请求头不存在 Token,则可能是执行登陆操作或者是游客状态访问,无需检查 token,直接返回 true
            return true;
        }
    
        /**
         * 判断用户是否想要登入。
         * 检测 header 里面是否包含 Token 字段
         */
        @Override
        protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
            HttpServletRequest req = (HttpServletRequest) request;
            String token = req.getHeader("Token");
            return token != null;
        }
    
        /**
         * 执行登陆操作
         */
        @Override
        protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            String token = httpServletRequest.getHeader("Token");
            JWTToken jwtToken = new JWTToken(token);
            // 提交给realm进行登入,如果错误他会抛出异常并被捕获
            getSubject(request, response).login(jwtToken);
            // 如果没有抛出异常则代表登入成功,返回true
            return true;
        }
    
        /**
         * 将非法请求跳转到 /unauthorized/**
         */
        private void responseError(ServletResponse response, String message) {
            try {
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                //设置编码,否则中文字符在重定向时会变为空字符串
                message = URLEncoder.encode(message, "UTF-8");
                httpServletResponse.sendRedirect("/unauthorized/" + message);
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
    }
    
  • UserRealm

    public class UserRealm extends AuthorizingRealm {
        @Resource
        UserService userService;
        /**
         * 重写supports方法,使之能识别JWTToken
         */
        @Override
        public boolean supports(AuthenticationToken token) {
            return token instanceof JWTToken;
        }
        //认证
          @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            // 已经用JWTToken代替了原有token,所以这里获取的凭据可以用JWTUtil解密
            String token = (String) authenticationToken.getCredentials();
            // 解密获得username,用于和数据库进行对比
            String username = JWTUtil.getUsername(token);
            if (username == null || !JWTUtil.verify(token, username)) {
                throw new AuthenticationException("token认证失败!");
            }
            String password = userService.getPassword(username);
            if (password == null) {
                throw new AuthenticationException("该用户不存在!");
            }
            return new SimpleAuthenticationInfo(username, token, this.getName());
        }
        //授权
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
            String username = JWTUtil.getUsername(principals.toString());
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            User user = userService.getUserByUserName(userName);
            for (SysRole role : user.getRoles()) {
                info.addRole(role.getName());
                for (SysPermission permission : role.getPermissions()) {
                    info.addStringPermission(permission.getName());
                }
            }
            return info;
        }
    }
    
  • ShiroConfig

    更改ShiroConfig中getShiroFilterFactoryBean方法的内容,使用JWTFilter

    	@Bean(name = "shiroFilter")
        public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
            ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
            // 添加自己的过滤器并且取名为jwt
            Map<String, Filter> filterMap = new LinkedHashMap<>();
            //设置我们自定义的JWT过滤器
            filterMap.put("jwt", new JWTFilter());
            bean.setFilters(filterMap);
            Map<String, String> map = new HashMap<>();
            // 所有请求通过我们自己的JWT Filter
            map.put("/**", "jwt");
            // 访问 /unauthorized/** 不通过JWTFilter
            map.put("/unauthorized/**", "anon");
            bean.setFilterChainDefinitionMap(map);
            bean.setSecurityManager(securityManager);
            // 设置无权限时跳转的 url;
            bean.setUnauthorizedUrl("/unauthorized/无权限");
            return bean;
        }
    

CacheManager

缓存作用

  • Cache 缓存: 计算机内存中一段数据

  • 作用: 用来减轻DB的访问压力,从而提高系统的查询效率

  • 流程:

    image-20200530090656417

EhCache缓存实现

  • pom

    <!--引入shiro和ehcache-->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>1.5.3</version>
    </dependency>
    
  • 开启缓存

    	//3.创建自定义realm
        @Bean
        public Realm getRealm(){
            CustomerRealm customerRealm = new CustomerRealm();
            //修改凭证校验匹配器
            HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
            //设置加密算法为md5
            credentialsMatcher.setHashAlgorithmName("MD5");
            //设置散列次数
            credentialsMatcher.setHashIterations(1024);
            customerRealm.setCredentialsMatcher(credentialsMatcher);
    
            //开启缓存管理器
            customerRealm.setCachingEnabled(true);
            customerRealm.setAuthorizationCachingEnabled(true);
            customerRealm.setAuthorizationCachingEnabled(true);
            customerRealm.setCacheManager(new EhCacheManager());
            return customerRealm;
        }
    

Redis缓存实现

  • pom

    <!--redis-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  • application.yml

    spring:
      redis:
        port: 6379
        host: localhost
        database: 0
    
  • 启动redis

    ./redis-server redis.conf
    
  • 缓存管理器

    • RedisCache

      public class RedisCache<k, v> implements Cache<k, v> {
          private String cacheName;
      
          public RedisCache() {
          }
      
          public RedisCache(String cacheName) {
              this.cacheName = cacheName;
          }
      
          @Override
          public v get(k k) throws CacheException {
              System.out.println("get key:" + k);
              return (v) getRedisTemplate().opsForHash().get(this.cacheName, k.toString());
          }
      
          @Override
          public v put(k k, v v) throws CacheException {
              System.out.println("put key: " + k);
              System.out.println("put value:" + v);
              getRedisTemplate().opsForHash().put(this.cacheName, k.toString(), v);
              return null;
          }
      
          @Override
          public v remove(k k) throws CacheException {
              System.out.println("=============remove=============");
              return (v) getRedisTemplate().opsForHash().delete(this.cacheName, k.toString());
          }
      
          @Override
          public void clear() throws CacheException {
              System.out.println("=============clear==============");
              getRedisTemplate().delete(this.cacheName);
          }
      
          @Override
          public int size() {
              return getRedisTemplate().opsForHash().size(this.cacheName).intValue();
          }
      
          @Override
          public Set<k> keys() {
              return getRedisTemplate().opsForHash().keys(this.cacheName);
          }
      
          @Override
          public Collection<v> values() {
              return getRedisTemplate().opsForHash().values(this.cacheName);
          }
      
          private RedisTemplate getRedisTemplate() {
              RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtils.getBean("redisTemplate");
              redisTemplate.setKeySerializer(new StringRedisSerializer());
              redisTemplate.setHashKeySerializer(new StringRedisSerializer());
              return redisTemplate;
          }
      }
      
    • RedisCacheManager

      public class RedisCacheManager implements CacheManager {
          @Override
          public <K, V> Cache<K, V> getCache(String cacheName) throws CacheException {
              return new RedisCache<K, V>(cacheName);
          }
      }
      
    • Shiroconfig

      @Configuration
      public class Shiroconfig {
          // 1.创建shiroFilter
          @Bean
          public ShiroFilterFactoryBean getShiroFilterFactoryBean(
                  DefaultWebSecurityManager defaultWebSecurityManager) {
              ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
              // 设置安全管理器
              shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
              // 配置系统受限资源
              // 配置系统公共资源
              Map<String, String> map = new HashMap<>();
              // authc 需要认证和授权
              map.put("/user/**", "anon");
              map.put("/register.jsp", "anon");
              map.put("/**", "authc");
              // 默认认证界面路径
              shiroFilterFactoryBean.setLoginUrl("/login.jsp");
              shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
              return shiroFilterFactoryBean;
          }
      
          // 创建安全管理器
          @Bean
          public DefaultWebSecurityManager getDefaultWebSecurityManager(Realm realm) {
              DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
              // 设置自定义realm
              defaultWebSecurityManager.setRealm(realm);
              return defaultWebSecurityManager;
          }
      
          // 创建自定义realm
          @Bean
          public Realm getRealm() {
              CustomerRealm customerRealm = new CustomerRealm();
              HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
              credentialsMatcher.setHashAlgorithmName("md5");
              credentialsMatcher.setHashIterations(1024);
              customerRealm.setCredentialsMatcher(credentialsMatcher);
              //开启缓存管理器
              customerRealm.setCachingEnabled(true);
              customerRealm.setAuthorizationCachingEnabled(true);
              customerRealm.setAuthorizationCachingEnabled(true);
              customerRealm.setCacheManager(new RedisCacheManager());
              return customerRealm;
          }
      }
      
  • salt序列化

    • MyByteSource

      public class MyByteSource implements ByteSource, Serializable {
          private byte[] bytes;
          private String cachedHex;
          private String cachedBase64;
      
          public MyByteSource() {
      
          }
      
          public MyByteSource(byte[] bytes) {
              this.bytes = bytes;
          }
      
          public MyByteSource(char[] chars) {
              this.bytes = CodecSupport.toBytes(chars);
          }
      
          public MyByteSource(String string) {
              this.bytes = CodecSupport.toBytes(string);
          }
      
          public MyByteSource(ByteSource source) {
              this.bytes = source.getBytes();
          }
      
          public MyByteSource(File file) {
              this.bytes = (new com.nuc.springboot_jsp_shiro.salt.MyByteSource.BytesHelper()).getBytes(file);
          }
      
          public MyByteSource(InputStream stream) {
              this.bytes = (new com.nuc.springboot_jsp_shiro.salt.MyByteSource.BytesHelper()).getBytes(stream);
          }
      
          public static boolean isCompatible(Object o) {
              return o instanceof byte[] || o instanceof char[] || o instanceof String || o instanceof ByteSource || o instanceof File || o instanceof InputStream;
          }
      
          @Override
          public byte[] getBytes() {
              return this.bytes;
          }
      
          @Override
          public boolean isEmpty() {
              return this.bytes == null || this.bytes.length == 0;
          }
      
          @Override
          public String toHex() {
              if (this.cachedHex == null) {
                  this.cachedHex = Hex.encodeToString(this.getBytes());
              }
      
              return this.cachedHex;
          }
      
          @Override
          public String toBase64() {
              if (this.cachedBase64 == null) {
                  this.cachedBase64 = Base64.encodeToString(this.getBytes());
              }
      
              return this.cachedBase64;
          }
      
          @Override
          public String toString() {
              return this.toBase64();
          }
      
          @Override
          public int hashCode() {
              return this.bytes != null && this.bytes.length != 0 ? Arrays.hashCode(this.bytes) : 0;
          }
      
          @Override
          public boolean equals(Object o) {
              if (o == this) {
                  return true;
              } else if (o instanceof ByteSource) {
                  ByteSource bs = (ByteSource) o;
                  return Arrays.equals(this.getBytes(), bs.getBytes());
              } else {
                  return false;
              }
          }
      
          private static final class BytesHelper extends CodecSupport {
              private BytesHelper() {
              }
      
              public byte[] getBytes(File file) {
                  return this.toBytes(file);
              }
      
              public byte[] getBytes(InputStream stream) {
                  return this.toBytes(stream);
              }
          }
      }
      
    • CustomRealm

      public class CustomerRealm extends AuthorizingRealm {
          @Resource
          private UserService userService;
      
          @Override
          protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
              String principal = (String) principals.getPrimaryPrincipal();
              List<Role> roles = userService.findRolesByUserName(principal);
              if (!CollectionUtils.isEmpty(roles)) {
                  SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
                  roles.forEach(role -> {
                      info.addRole(role.getName());
                      List<Perms> perms = userService.findPermsByRoleId(role.getId());
                      if (!CollectionUtils.isEmpty(perms) && perms.get(0) != null) {
                          perms.forEach(perm -> {
                              info.addStringPermission(perm.getName());
                          });
                      }
                  });
                  return info;
              }
              return null;
          }
      
          @Override
          protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
                  throws AuthenticationException {
              User user = userService.findByUsername((String) token.getPrincipal());
              if (!ObjectUtils.isEmpty(user)) {
                  return new SimpleAuthenticationInfo(
                          user.getUsername(),
                          user.getPassword(),
                          MyByteSource.Util.bytes(user.getSalt()),
                          this.getName());
              }
              return null;
          }
      }
      

验证码

  • 验证码工具类

    public class VerifyCodeUtils {
        // 使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
        public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
        private static Random random = new Random();
    
    
        /**
         * 使用系统默认字符源生成验证码
         *
         * @param verifySize 验证码长度
         * @return
         */
        public static String generateVerifyCode(int verifySize) {
            return generateVerifyCode(verifySize, VERIFY_CODES);
        }
    
        /**
         * 使用指定源生成验证码
         *
         * @param verifySize 验证码长度
         * @param sources    验证码字符源
         * @return
         */
        public static String generateVerifyCode(int verifySize, String sources) {
            if (sources == null || sources.length() == 0) {
                sources = VERIFY_CODES;
            }
            int codesLen = sources.length();
            Random rand = new Random(System.currentTimeMillis());
            StringBuilder verifyCode = new StringBuilder(verifySize);
            for (int i = 0; i < verifySize; i++) {
                verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
            }
            return verifyCode.toString();
        }
    
        /**
         * 生成随机验证码文件,并返回验证码值
         *
         * @param w
         * @param h
         * @param outputFile
         * @param verifySize
         * @return
         * @throws IOException
         */
        public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException {
            String verifyCode = generateVerifyCode(verifySize);
            outputImage(w, h, outputFile, verifyCode);
            return verifyCode;
        }
    
        /**
         * 输出随机验证码图片流,并返回验证码值
         *
         * @param w
         * @param h
         * @param os
         * @param verifySize
         * @return
         * @throws IOException
         */
        public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException {
            String verifyCode = generateVerifyCode(verifySize);
            outputImage(w, h, os, verifyCode);
            return verifyCode;
        }
    
        /**
         * 生成指定验证码图像文件
         *
         * @param w
         * @param h
         * @param outputFile
         * @param code
         * @throws IOException
         */
        public static void outputImage(int w, int h, File outputFile, String code) throws IOException {
            if (outputFile == null) {
                return;
            }
            File dir = outputFile.getParentFile();
            if (!dir.exists()) {
                dir.mkdirs();
            }
            try {
                outputFile.createNewFile();
                FileOutputStream fos = new FileOutputStream(outputFile);
                outputImage(w, h, fos, code);
                fos.close();
            } catch (IOException e) {
                throw e;
            }
        }
    
        /**
         * 输出指定验证码图片流
         *
         * @param w
         * @param h
         * @param os
         * @param code
         * @throws IOException
         */
        public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
            int verifySize = code.length();
            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Random rand = new Random();
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            Color[] colors = new Color[5];
            Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
                    Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                    Color.PINK, Color.YELLOW};
            float[] fractions = new float[colors.length];
            for (int i = 0; i < colors.length; i++) {
                colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
                fractions[i] = rand.nextFloat();
            }
            Arrays.sort(fractions);
    
            g2.setColor(Color.GRAY);// 设置边框色
            g2.fillRect(0, 0, w, h);
    
            Color c = getRandColor(200, 250);
            g2.setColor(c);// 设置背景色
            g2.fillRect(0, 2, w, h - 4);
    
            //绘制干扰线
            Random random = new Random();
            g2.setColor(getRandColor(160, 200));// 设置线条的颜色
            for (int i = 0; i < 20; i++) {
                int x = random.nextInt(w - 1);
                int y = random.nextInt(h - 1);
                int xl = random.nextInt(6) + 1;
                int yl = random.nextInt(12) + 1;
                g2.drawLine(x, y, x + xl + 40, y + yl + 20);
            }
    
            // 添加噪点
            float yawpRate = 0.05f;// 噪声率
            int area = (int) (yawpRate * w * h);
            for (int i = 0; i < area; i++) {
                int x = random.nextInt(w);
                int y = random.nextInt(h);
                int rgb = getRandomIntColor();
                image.setRGB(x, y, rgb);
            }
    
            shear(g2, w, h, c);// 使图片扭曲
    
            g2.setColor(getRandColor(100, 160));
            int fontSize = h - 4;
            Font font = new Font("Algerian", Font.ITALIC, fontSize);
            g2.setFont(font);
            char[] chars = code.toCharArray();
            for (int i = 0; i < verifySize; i++) {
                AffineTransform affine = new AffineTransform();
                affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
                g2.setTransform(affine);
                g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
            }
    
            g2.dispose();
            ImageIO.write(image, "jpg", os);
        }
    
        private static Color getRandColor(int fc, int bc) {
            if (fc > 255) {
                fc = 255;
            }
            if (bc > 255) {
                bc = 255;
            }
            int r = fc + random.nextInt(bc - fc);
            int g = fc + random.nextInt(bc - fc);
            int b = fc + random.nextInt(bc - fc);
            return new Color(r, g, b);
        }
    
        private static int getRandomIntColor() {
            int[] rgb = getRandomRgb();
            int color = 0;
            for (int c : rgb) {
                color = color << 8;
                color = color | c;
            }
            return color;
        }
    
        private static int[] getRandomRgb() {
            int[] rgb = new int[3];
            for (int i = 0; i < 3; i++) {
                rgb[i] = random.nextInt(255);
            }
            return rgb;
        }
    
        private static void shear(Graphics g, int w1, int h1, Color color) {
            shearX(g, w1, h1, color);
            shearY(g, w1, h1, color);
        }
    
        private static void shearX(Graphics g, int w1, int h1, Color color) {
    
            int period = random.nextInt(2);
    
            boolean borderGap = true;
            int frames = 1;
            int phase = random.nextInt(2);
    
            for (int i = 0; i < h1; i++) {
                double d = (double) (period >> 1)
                        * Math.sin((double) i / (double) period
                        + (6.2831853071795862D * (double) phase)
                        / (double) frames);
                g.copyArea(0, i, w1, 1, (int) d, 0);
                if (borderGap) {
                    g.setColor(color);
                    g.drawLine((int) d, i, 0, i);
                    g.drawLine((int) d + w1, i, w1, i);
                }
            }
    
        }
    
        private static void shearY(Graphics g, int w1, int h1, Color color) {
    
            int period = random.nextInt(40) + 10; // 50;
    
            boolean borderGap = true;
            int frames = 20;
            int phase = 7;
            for (int i = 0; i < w1; i++) {
                double d = (double) (period >> 1)
                        * Math.sin((double) i / (double) period
                        + (6.2831853071795862D * (double) phase)
                        / (double) frames);
                g.copyArea(i, 0, 1, h1, 0, (int) d);
                if (borderGap) {
                    g.setColor(color);
                    g.drawLine(i, (int) d, i, 0);
                    g.drawLine(i, (int) d + h1, i, h1);
                }
    
            }
    
        }
    
        public static void main(String[] args) throws IOException {
            //获取验证码
            String s = generateVerifyCode(4);
            //将验证码放入图片中
            outputImage(260, 60, new File("/Users/chenyannan/Desktop/安工资料/aa.jpg"), s);
            System.out.println(s);
        }
    }
    
  • index.jsp

    <form action="${pageContext.request.contextPath}/user/login" method="post">
        用户名:<input type="text" name="username"> <br/>
        密&nbsp;&nbsp;&nbsp;码:<input type="text" name="password"> <br>
        请输入验证码: <input type="text" name="code"><img src=`"${pageContext.request.contextPath}/user/getImage"` alt=""><br>
        <input type="submit" value="登录">
    </form>
    
  • userController

    创建图片接口,并修改认证流程

        @RequestMapping("/login")
        public String login(String username, String password, String code, HttpSession session) {
            String codes = (String) session.getAttribute("code");
            try {
                if (codes.equalsIgnoreCase(code)) {
                    //获取主体对象
                    Subject subject = SecurityUtils.getSubject();
                    subject.login(new UsernamePasswordToken(username, password));
                    return "redirect:/index.jsp";
                } else {
                    throw new RuntimeException("验证码错误!");
                }
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                System.out.println("用户名错误!");
            } catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                System.out.println("密码错误!");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            return "redirect:/login.jsp";
        }
    
    	//图片接口
        @RequestMapping("getImage")
        public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
            //生成验证码
            String code = VerifyCodeUtils.generateVerifyCode(4);
            //验证码放入session
            session.setAttribute("code", code);
            //验证码存入图片
            ServletOutputStream os = response.getOutputStream();
            response.setContentType("image/png");
            VerifyCodeUtils.outputImage(220, 60, os, code);
        }
    

springboot整合thymeleaf

简单使用

  • pom

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-thymeleaf</artifactId>
            </dependency>
            <dependency>
                <groupId>com.github.theborakompanioni</groupId>
                <artifactId>thymeleaf-extras-shiro</artifactId>
                <version>2.1.0</version>
            </dependency>
    
  • ShiroConfig

    // 配置方言
    	@Bean(name = "shiroDialect")
        public ShiroDialect shiroDialect() {
            return new ShiroDialect();
        }
    //配置权限
            map.put("/user/**", "anon");
            map.put("/**", "authc");
            // 默认认证界面路径
            shiroFilterFactoryBean.setLoginUrl("/user/toLogin");
    
  • UserController

    将页面的跳转写成接口,注意修改原有重定向代码

    @Controller
    @RequestMapping("/user")
    public class UserController {
        @Resource
        private UserService userService;
    
        @RequestMapping("toLogin")
        public String login() {
            return "login";
        }
    
        @RequestMapping("toRegister")
        public String register() {
            return "register";
        }
    
        @RequestMapping("toIndex")
        public String index() {
            return "index";
        }
    
        @RequestMapping("register")
        public String register(User user) {
            try {
                userService.register(user);
                return "redirect:/user/toLogin";
            } catch (Exception e) {
                e.printStackTrace();
                return "redirect:/user/toRegister";
            }
        }
    
        @RequestMapping("/login")
        public String login(String username, String password, String code, HttpSession session) {
            String codes = (String) session.getAttribute("code");
            try {
                if (codes.equalsIgnoreCase(code)) {
                    //获取主体对象
                    Subject subject = SecurityUtils.getSubject();
                    subject.login(new UsernamePasswordToken(username, password));
                    return "redirect:/user/toIndex";
                } else {
                    throw new RuntimeException("验证码错误!");
                }
            } catch (UnknownAccountException e) {
                e.printStackTrace();
                System.out.println("用户名错误!");
            } catch (IncorrectCredentialsException e) {
                e.printStackTrace();
                System.out.println("密码错误!");
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            return "redirect:/user/toLogin";
        }
    
        @RequestMapping("logout")
        public String logout() {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return "redirect:/user/toLogin";
        }
    
        @RequestMapping("getImage")
        public void getImage(HttpSession session, HttpServletResponse response) throws IOException {
            //生成验证码
            String code = VerifyCodeUtils.generateVerifyCode(4);
            //验证码放入session
            session.setAttribute("code", code);
            //验证码存入图片
            ServletOutputStream os = response.getOutputStream();
            response.setContentType("image/png");
            VerifyCodeUtils.outputImage(220, 60, os, code);
        }
    
    }
    
  • html

    注意HTML语法

    login.html

    <!doctype html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
              name="viewport">
        <meta content="ie=edge" http-equiv="X-UA-Compatible">
        <title>Document</title>
    </head>
    <body>
    <h1>登录界面</h1>
    <form method="post" th:action="@{/user/login}">
        用户名:<input name="username" type="text"> <br/>
        密&nbsp;&nbsp;&nbsp;码:<input name="password" type="text"> <br>
        请输入验证码: <input name="code" type="text"><img alt="" th:src="@{/user/getImage}"><br>
        <input type="submit" value="登录">
        <a th:href="@{/user/toRegister} ">点我去注册</a>
    
    </form>
    </body>
    </html>
    

    register.html

    <!doctype html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
              name="viewport">
        <meta content="ie=edge" http-equiv="X-UA-Compatible">
        <title>Document</title>
    </head>
    <body>
    <h1>注册界面</h1>
    <form method="post" th:action="@{/user/register}">
        用户名:<input name="username" type="text"> <br/>
        密&nbsp;&nbsp;&nbsp;码:<input name="password" type="text"> <br>
        <input type="submit" value="注册">
    </form>
    </body>
    </html>
    

    index.html

    <!doctype html>
    <html xmlns="http://www.w3.org/1999/xhtml" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro"
          xmlns:th="http://www.thymeleaf.org">
    
    <head>
        <meta charset="UTF-8">
        <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
              name="viewport">
        <meta content="ie=edge" http-equiv="X-UA-Compatible">
        <title>Document</title>
    </head>
    <body>
    <h1>系统主页</h1>
    <a th:href="@{/user/logout}">退出登录</a>
    <ul>
        <span shiro:principal=""></span>
        <shiro:hasAnyRoles name="user_manager,admin,addinfo_manager">
            <li><a href="">用户管理</a>
                <ul>
                    <shiro:hasPermission name="user:add:*">
                        <li><a href="">添加</a></li>
                    </shiro:hasPermission>
                    <shiro:hasPermission name="user:delete:*">
                        <li><a href="">删除</a></li>
                    </shiro:hasPermission>
                    <shiro:hasPermission name="user:update:*">
                        <li><a href="">修改</a></li>
                    </shiro:hasPermission>
                    <shiro:hasPermission name="user:find:*">
                        <li><a href="">查询</a></li>
                    </shiro:hasPermission>
                </ul>
            </li>
        </shiro:hasAnyRoles>
        <shiro:hasAnyRoles name="order_manager,admin,addinfo_manager">
            <li><a href="">订单管理</a></li>
            <ul>
                <shiro:hasPermission name="order:add:*">
                    <li><a href="">添加</a></li>
                </shiro:hasPermission>
                <shiro:hasPermission name="order:delete:*">
                    <li><a href="">删除</a></li>
                </shiro:hasPermission>
                <shiro:hasPermission name="order:update:*">
                    <li><a href="">修改</a></li>
                </shiro:hasPermission>
                <shiro:hasPermission name="order:find:*">
                    <li><a href="">查询</a></li>
                </shiro:hasPermission>
            </ul>
        </shiro:hasAnyRoles>
        <shiro:hasRole name="admin">
            <li><a href="">商品管理</a></li>
            <li><a href="">物流管理</a></li>
        </shiro:hasRole>
    
        <shiro:hasRole name="user">
            <li><a href="">公共资源</a></li>
        </shiro:hasRole>
    </ul>
    </body>
    </html>
    

常见标签

<!-- 验证当前用户是否为“访客”,即未认证(包含未记住)的用户。 -->
<p shiro:guest="">Please <a href="login.html">login</a></p>


<!-- 认证通过或已记住的用户。 -->
<p shiro:user="">
    Welcome back John! Not John? Click <a href="login.html">here</a> to login.
</p>

<!-- 已认证通过的用户。不包含已记住的用户,这是与user标签的区别所在。 -->
<p shiro:authenticated="">
    Hello, <span shiro:principal=""></span>, how are you today?
</p>
<a shiro:authenticated="" href="updateAccount.html">Update your contact information</a>

<!-- 输出当前用户信息,通常为登录帐号信息。 -->
<p>Hello, <shiro:principal/>, how are you today?</p>


<!-- 未认证通过用户,与authenticated标签相对应。与guest标签的区别是,该标签包含已记住用户。 -->
<p shiro:notAuthenticated="">
    Please <a href="login.html">login</a> in order to update your credit card information.
</p>

<!-- 验证当前用户是否属于该角色。 -->
<a shiro:hasRole="admin" href="admin.html">Administer the system</a><!-- 拥有该角色 -->

<!-- 与hasRole标签逻辑相反,当用户不属于该角色时验证通过。 -->
<p shiro:lacksRole="developer"><!-- 没有该角色 -->
    Sorry, you are not allowed to developer the system.
</p>

<!-- 验证当前用户是否属于以下所有角色。 -->
<p shiro:hasAllRoles="developer, 2"><!-- 角色与判断 -->
    You are a developer and a admin.
</p>

<!-- 验证当前用户是否属于以下任意一个角色。  -->
<p shiro:hasAnyRoles="admin, vip, developer,1"><!-- 角色或判断 -->
    You are a admin, vip, or developer.
</p>

<!--验证当前用户是否拥有指定权限。  -->
<a shiro:hasPermission="userInfo:add" href="createUser.html">添加用户</a><!-- 拥有权限 -->

<!-- 与hasPermission标签逻辑相反,当前用户没有制定权限时,验证通过。 -->
<p shiro:lacksPermission="userInfo:del"><!-- 没有权限 -->
    Sorry, you are not allowed to delete user accounts.
</p>

<!-- 验证当前用户是否拥有以下所有角色。 -->
<p shiro:hasAllPermissions="userInfo:view, userInfo:add"><!-- 权限与判断 -->
    You can see or add users.
</p>

<!-- 验证当前用户是否拥有以下任意一个权限。  -->
<p shiro:hasAnyPermissions="userInfo:view, userInfo:del"><!-- 权限或判断 -->
    You can see or delete users.
</p>
<a shiro:hasPermission="pp" href="createUser.html">Create a new User</a>

参考链接

posted @ 2022-01-02 22:49  Faetbwac  阅读(92)  评论(0编辑  收藏  举报