【鉴权架构】SpringBoot + Sa-Token + MyBatis + MySQL + Redis 实现用户鉴权、角色管理、权限管理

sa-token 官方文档

基础登录功能

  1. 引入依赖

由于使用SpringBoot3,故使用较新版

        <!-- Sa-Token 权限认证,在线文档:https://sa-token.*** -->
        <dependency>
            <groupId>***.dev33</groupId>
            <artifactId>sa-token-spring-boot3-starter</artifactId>
            <version>1.44.0</version>
        </dependency>
  1. yml配置

前端小程序使用,故禁用session,使用token模式

# 用户鉴权
sa-token:
  # token 名称
  # Authorization: Bearer token值
  token-name: Authorization
  token-prefix: Bearer       # 设置Token前缀 【注意有空格】
  is-read-header: true          # 从Header读取Token
  is-read-cookie: false         # 禁用Cookie(纯Token模式)
  # token 有效期(单位:秒) 默认30天,-1 代表永久有效
  timeout: 2592000
  # token 最低活跃频率(单位:秒),如果 token 超过此时间没有访问系统就会被冻结,默认-1 代表不限制,永不冻结
  active-timeout: -1
  # 是否允许同一账号多地同时登录 (为 true 时允许一起登录, 为 false 时新登录挤掉旧登录)
  is-concurrent: true
  # 在多人登录同一账号时,是否共用一个 token (为 true 时所有登录共用一个 token, 为 false 时每次登录新建一个 token)
  is-share: false
  # token 风格(默认可取值:uuid、simple-uuid、random-32、random-64、random-128、tik)
  token-style: uuid
  # 是否输出操作日志
  is-log: true
  1. 全局拦截器 拦截未登录用户

新建全局拦截器 实现 WebMv***onfigurer 接口

@Configuration
public class SaTokenConfig implements WebMv***onfigurer {
   
   
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
   
   
        // 注册Sa-Token拦截器
        registry.addInterceptor(new SaInterceptor(handler -> {
   
   
            SaRouter.match("/**")
            .notMatch(
                // 用户认证
                "/user/login",
                "/user/register",

                // Swagger/Knife4j 接口文档
                "/doc.html",
                "/webjars/**",
                "/swagger-resources/**",
                "/v3/api-docs",
                "/v3/api-docs/**",
                "/favicon.ico",

                // 其他需要放行的路径
                "/error"
            )
            .check(StpUtil::checkLogin); // 校验是否登录 (调试阶段可放开)
        })).addPathPatterns("/**");
    }
}

  1. 在用户登录服务中使用 StpUtil 服务进行登录

satoken 会在内存中保存 id 和 token,标记用户登录

StpUtil.login(user.getId()); // 生成Token并保存
    @Override
    public LoginUserVO userLogin(String userA***ount, String userPassword) {
   
   
        // 1. 校验
        if (StrUtil.hasBlank(userA***ount, userPassword)) {
   
   
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userA***ount.length() < 4) {
   
   
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号错误");
        }
        
转载请说明出处内容投诉
CSS教程网 » 【鉴权架构】SpringBoot + Sa-Token + MyBatis + MySQL + Redis 实现用户鉴权、角色管理、权限管理

发表评论

欢迎 访客 发表评论

一个令你着迷的主题!

查看演示 官网购买