当前位置:   article > 正文

SpringBoot 3 集成 Sa-Token 实现权限相关功能_satoken springboot3

satoken springboot3

1、Sa-Token 介绍

1.1 Sa-Token 开发文档:https://sa-token.cc

1.2 Sa-Token 是一个轻量级 Java 权限认证框架,主要解决:登录认证权限认证单点登录OAuth2.0微服务鉴权 等一系列权限相关问题。

1.3 功能结构图

2、 SpringBoot 3 集成 Sa-Token

2.1 Maven

  1. <!-- Sa-Token -->
  2. <dependency>
  3. <groupId>cn.dev33</groupId>
  4. <artifactId>sa-token-spring-boot3-starter</artifactId>
  5. <version>1.38.0</version>
  6. </dependency>
  7. <!-- Sa-Token 集成 jwt -->
  8. <dependency>
  9. <groupId>cn.dev33</groupId>
  10. <artifactId>sa-token-jwt</artifactId>
  11. <version>1.38.0</version>
  12. </dependency>
  13. <!-- Sa-Token 集成 redis, 并使用 jackson 序列化 -->
  14. <dependency>
  15. <groupId>cn.dev33</groupId>
  16. <artifactId>sa-token-redis-jackson</artifactId>
  17. <version>1.38.0</version>
  18. </dependency>
  19. <!-- 提供Redis连接池 -->
  20. <dependency>
  21. <groupId>org.apache.commons</groupId>
  22. <artifactId>commons-pool2</artifactId>
  23. </dependency>
  24. <!-- fastjson2 处理 json 数据 -->
  25. <dependency>
  26. <groupId>com.alibaba.fastjson2</groupId>
  27. <artifactId>fastjson2</artifactId>
  28. <version>2.0.48</version>
  29. </dependency>
  30. <!-- 使用 springdoc 生成 swagger 文档 -->
  31. <dependency>
  32. <groupId>org.springdoc</groupId>
  33. <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  34. <version>2.5.0</version>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-web</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>com.mysql</groupId>
  42. <artifactId>mysql-connector-j</artifactId>
  43. <version>8.3.0</version>
  44. </dependency>
  45. <!-- mybatis-plus-boot-starter 中 mybatis-spring 版本不够,排除之后引入新版本 -->
  46. <dependency>
  47. <groupId>com.baomidou</groupId>
  48. <artifactId>mybatis-plus-boot-starter</artifactId>
  49. <version>3.5.6</version>
  50. <exclusions>
  51. <exclusion>
  52. <groupId>org.mybatis</groupId>
  53. <artifactId>mybatis-spring</artifactId>
  54. </exclusion>
  55. </exclusions>
  56. </dependency>
  57. <dependency>
  58. <groupId>org.mybatis</groupId>
  59. <artifactId>mybatis-spring</artifactId>
  60. <version>3.0.3</version>
  61. </dependency>

2.2 yml 配置 sa-token

  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. driver-class-name: com.mysql.cj.jdbc.Driver
  6. url: jdbc:mysql://localhost:3306/xxx
  7. username: xxx
  8. password: xxx
  9. data:
  10. redis:
  11. database: 1
  12. sa-token:
  13. token-name: X-Token
  14. # token有效期,单位s 默认30天, -1代表永不过期
  15. timeout: -1
  16. # token 最低活跃频率(单位:秒),如果 token 超过此时间没有访问系统就会被冻结,默认-1 代表不限制,永不冻结
  17. active-timeout: 3600
  18. # jwt秘钥
  19. jwt-secret-key: qazwsxedc
  20. # 文件上传下载目录
  21. files:
  22. upload:
  23. path: D:/files/

2.3 常量

  1. package com.dragon.springboot3vue3.common;
  2. import io.swagger.v3.oas.annotations.media.Schema;
  3. @Schema(description = "常量")
  4. public class Constant {
  5. // SaResult 默认设置了 200 为成功, 500 为 失败
  6. /********** CODE & MSG **********/
  7. public static final String TOKEN= "X-Token";
  8. public static final String USER_PASSWORD= "123456";
  9. public static final int TOKEN_INVALID_CODE = 20001; public static final String TOKEN_INVALID_MSG = "Token无效,请重新登录";
  10. public static final int USERNAME_OCCUPIED_CODE = 20002; public static final String USERNAME_OCCUPIED_MSG = "用户名被占用,请重新输入";
  11. public static final int USERNAME_OR_PASSWORD_ERROR_CODE = 20003; public static final String USERNAME_OR_PASSWORD_ERROR_MSG = "用户名或密码输入错误";
  12. public static final int MISSING_NECESSARY_PARAMETERS_CODE = 20004; public static final String MISSING_NECESSARY_PARAMETERS_MSG = "缺少必要的参数";
  13. public static final int ORIGINAL_PASSWORD_ERROR_CODE = 20005; public static final String ORIGINAL_PASSWORD_ERROR_MSG = "原密码输入错误";
  14. public static final int PASSWORD_INCONSISTENCY_CODE = 20006; public static final String PASSWORD_INCONSISTENCY_MSG = "两次输入的新密码不一致";
  15. // 请求白名单,请求会放行
  16. public static final String[] WHITE_LIST = {
  17. "/user/register",
  18. "/user/login",
  19. "/user/logout",
  20. "/swagger-ui/**",
  21. "/v3/**",
  22. "/files/{fileName}",
  23. };
  24. }

2.4 config-配置类

2.4.1 跨域配置类

  1. package com.dragon.springboot3vue3.config;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.cors.CorsConfiguration;
  5. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
  6. import org.springframework.web.filter.CorsFilter;
  7. import java.util.List;
  8. /**
  9. * 跨域配置类
  10. */
  11. @Configuration
  12. public class CorsConfig {
  13. @Bean
  14. public CorsFilter corsFilter(){
  15. CorsConfiguration corsConfiguration = new CorsConfiguration();
  16. corsConfiguration.setAllowedOrigins(List.of("http://localhost:3000", "http://127.0.0.1:5173","http://localhost:5173")); // 设置允许的来源
  17. corsConfiguration.setAllowedMethods(List.of("*")); // 设置允许的方法
  18. corsConfiguration.setAllowedHeaders(List.of("*")); // 设置允许的头部
  19. corsConfiguration.setAllowCredentials(true); // 允许携带凭证
  20. UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
  21. urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
  22. return new CorsFilter(urlBasedCorsConfigurationSource);
  23. }
  24. }

2.4.2 SaToken 配置类

  1. package com.dragon.springboot3vue3.config;
  2. import cn.dev33.satoken.interceptor.SaInterceptor;
  3. import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
  4. import cn.dev33.satoken.router.SaRouter;
  5. import cn.dev33.satoken.stp.StpLogic;
  6. import cn.dev33.satoken.stp.StpUtil;
  7. import com.dragon.springboot3vue3.common.Constant;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  11. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  12. @Configuration
  13. public class SaTokenConfigure implements WebMvcConfigurer {
  14. // Sa-Token 整合 jwt (Simple 简单模式)
  15. @Bean
  16. public StpLogic getStpLogicJwt() {
  17. return new StpLogicJwtForSimple();
  18. }
  19. // 注册 Sa-Token 拦截器
  20. @Override
  21. public void addInterceptors(InterceptorRegistry registry) {
  22. registry.addInterceptor(new SaInterceptor(handle -> {
  23. // 登录拦截,放行白名单
  24. SaRouter.match("/**").notMatch(Constant.WHITE_LIST).check(r -> StpUtil.checkLogin());
  25. }))
  26. .addPathPatterns("/**");
  27. }
  28. }

2.4.3 Swagger 配置类

  1. package com.dragon.springboot3vue3.config;
  2. import io.swagger.v3.oas.models.ExternalDocumentation;
  3. import io.swagger.v3.oas.models.OpenAPI;
  4. import io.swagger.v3.oas.models.info.Info;
  5. import io.swagger.v3.oas.models.info.License;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. @Configuration
  9. public class SwaggerConfig {
  10. @Bean
  11. public OpenAPI openAPI() {
  12. OpenAPI openAPI = new OpenAPI();
  13. openAPI.info(new Info().title("前后端分离管理系统")
  14. .description("使用springboot3-vue3等技术")
  15. .version("v1.0.0")
  16. .license(new License().name("Apache 2.0").url("https://springdoc.org")));
  17. openAPI.externalDocs(new ExternalDocumentation().description("项目API文档")
  18. .url("/"));
  19. return openAPI;
  20. }
  21. }

2.4.4 MybatisPlus 配置类

  1. package com.dragon.springboot3vue3.config;
  2. import com.baomidou.mybatisplus.annotation.DbType;
  3. import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
  4. import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. @Configuration
  8. public class MybatisPlusConfig {
  9. /**
  10. * 添加 MybatisPlus 分页插件
  11. */
  12. @Bean
  13. public MybatisPlusInterceptor mybatisPlusInterceptor() {
  14. MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
  15. interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
  16. return interceptor;
  17. }
  18. }

2.5 实现登录认证

2.5.1 SaResult - SaToken封装的结果集

2.5.2 StpUtil - SaToken的鉴权工具类(Sa-Token

2.5.3 StringRedisTemplate  - Redis工具类

2.5.4 BCrypt - 密码加密方式(Sa-Token

2.5.5 @Tag、@Operation -  Swagger(SpringDoc)注解

  1. package com.dragon.springboot3vue3.controller;
  2. import cn.dev33.satoken.secure.BCrypt;
  3. import cn.dev33.satoken.stp.StpUtil;
  4. import cn.dev33.satoken.util.SaResult;
  5. import com.alibaba.fastjson2.JSON;
  6. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  7. import com.dragon.springboot3vue3.common.Constant;
  8. import com.dragon.springboot3vue3.controller.dto.entityDto.RegisterOrLoginDto;
  9. import com.dragon.springboot3vue3.controller.dto.entityDto.UserDto;
  10. import com.dragon.springboot3vue3.controller.dto.pageDto.UserPageDto;
  11. import com.dragon.springboot3vue3.entity.User;
  12. import com.dragon.springboot3vue3.service.IUserService;
  13. import io.swagger.v3.oas.annotations.Operation;
  14. import io.swagger.v3.oas.annotations.tags.Tag;
  15. import jakarta.servlet.http.HttpServletResponse;
  16. import org.apache.commons.lang3.StringUtils;
  17. import org.springframework.beans.BeanUtils;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.data.redis.core.StringRedisTemplate;
  20. import org.springframework.validation.annotation.Validated;
  21. import org.springframework.web.bind.annotation.*;
  22. import org.springframework.web.multipart.MultipartFile;
  23. import java.util.List;
  24. import java.util.concurrent.TimeUnit;
  25. @Tag(name = "用户接口")
  26. @RestController
  27. @RequestMapping("/user")
  28. public class UserController {
  29. @Autowired
  30. private IUserService userService;
  31. @Autowired
  32. private StringRedisTemplate stringRedisTemplate;
  33. @Operation(summary = "注册")
  34. @PostMapping("/register")
  35. public SaResult register(@RequestBody @Validated RegisterOrLoginDto registerDto){
  36. User user=userService.lambdaQuery().eq(User::getUsername,registerDto.getUsername()).one();
  37. if(user!=null){
  38. return SaResult.error(Constant.USERNAME_OCCUPIED_MSG).setCode(Constant.USERNAME_OCCUPIED_CODE);
  39. }
  40. user=new User();
  41. BeanUtils.copyProperties(registerDto,user);
  42. // BCrypt.hashpw() 密码加密
  43. user.setPassword(BCrypt.hashpw(registerDto.getPassword(), BCrypt.gensalt()));
  44. userService.save(user);
  45. return SaResult.ok();
  46. }
  47. @Operation(summary = "登录")
  48. @PostMapping("/login")
  49. public SaResult login(@RequestBody @Validated RegisterOrLoginDto loginDto){
  50. User user=userService.lambdaQuery().eq(User::getUsername,loginDto.getUsername()).one();
  51. // BCrypt.checkpw(前端明文,后端密文)
  52. if(user!=null && BCrypt.checkpw(loginDto.getPassword(),user.getPassword())){
  53. // 登录认证
  54. StpUtil.login(user.getId());
  55. // 生成token,token 信息自动存入redis,在yml里配置 sa-token 相关信息
  56. String token = StpUtil.getTokenValue();
  57. // 将用户信息存入 redis
  58. stringRedisTemplate.opsForValue().set(user.getId(), JSON.toJSONString(user),1, TimeUnit.DAYS);
  59. return SaResult.ok().setData(token);
  60. }
  61. return SaResult.error(Constant.USERNAME_OR_PASSWORD_ERROR_MSG).setCode(Constant.USERNAME_OR_PASSWORD_ERROR_CODE);
  62. }
  63. @Operation(summary = "注销")
  64. @PostMapping("/logout")
  65. public SaResult logout(){
  66. StpUtil.logout();
  67. return SaResult.ok();
  68. }
  69. @Operation(summary = "获取登录用户信息")
  70. @GetMapping("/userInfo")
  71. public SaResult userInfo(){
  72. // Redis 中获取登录的用户信息
  73. String userInfo = stringRedisTemplate.opsForValue().get(StpUtil.getLoginIdAsString());
  74. User user= JSON.parseObject(userInfo,User.class);
  75. return SaResult.ok().setData(user);
  76. }
  77. }

2.6 swagger-ui地址:http://localhost:8080/swagger-ui/index.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/1006340
推荐阅读
相关标签
  

闽ICP备14008679号