spring boot3 集成jjwt(java-jwt)版本的

1、安装maven依赖

复制代码
<dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>4.5.1</version>
            <scope>compile</scope>
        </dependency>

2、新建用户模拟类,例如

复制代码
public class SystemUserVO extends BaseEntity {

    @NotNull(message = "账号不能为空")//空校验
    @NotBlank(message = "账号不能为空") //不能为空字符串
    private String account;

    private String password;

    @NotNull(message = "用户名不能为空")//空校验
    @NotBlank(message = "用户名不能为空") //不能为空字符串
    private String userName;


    private String nickName;

    @TableField(updateStrategy = FieldStrategy.ALWAYS)
    private String email;

    @TableField(updateStrategy = FieldStrategy.ALWAYS)
    private String phone;

    @TableField(updateStrategy = FieldStrategy.ALWAYS)
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate birthday;

    @NotNull(message = "性别不能为空")//空校验
    private Integer sex;

//    @NotNull(message = "用户平台不能为空")//空校验
    private Integer userType;

    @NotNull(message = "状态不能为空")//空校验
    private Integer status;
}

3、新建生成token类和解析方法

复制代码
package com.example.system_manage.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.system_manage.vo.SystemUserVO;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class JwtUtil {
    private static long expire_time = 1000 * 60 * 60 * 8;
    private static String signature = "xxxxxxxxx";

    public static String createToken(SystemUserVO user) {
        Date date = new Date(System.currentTimeMillis() + expire_time);
        Algorithm algorithm = Algorithm.HMAC256(signature);
        return JWT.create()
                // 将 user id 保存到 token 里面
                .withAudience(user.getId().toString())
                .withClaim("userName", user.getUserName())
                .withClaim("userId", user.getId())
                .withClaim("userAccount", user.getAccount())
                .withClaim("userType", user.getUserType())
                .withClaim("userTenantIds", user.getSystemUserTenantList().stream().map(v -> v.getUserTenantId().toString()).collect(Collectors.joining(",")))
                .withClaim("userRoleIds", user.getSystemUserRoleList().stream().map(v -> v.getRoleId().toString()).collect(Collectors.joining(",")))
                .withClaim("userDeptIds", user.getSystemUserDeptList().stream().map(v -> v.getDeptId().toString()).collect(Collectors.joining(",")))
                .withClaim("userPostIds", user.getSystemUserPostList().stream().map(v -> v.getPostId().toString()).collect(Collectors.joining(",")))
                // 60分钟后token过期
                .withExpiresAt(date)
                // token 的密钥
                .sign(algorithm);
    }


    /**
     * 接口解析token
     *
     * @param token
     * @return
     */
    public static Map<String, Object> getTokenInform(String token) {
        try {
            if (StringUtils.isBlank(token)) {
                throw new BusinessException("当前无验证令牌");
            }
            Algorithm algorithm = Algorithm.HMAC256(signature);
            JWTVerifier verifier = JWT.require(algorithm)
                    .build();
            DecodedJWT jwt=verifier.verify(token);
            Map<String, Object> result = new HashMap<>();
            result.put("userId", jwt.getClaim("userId").asLong().toString());
            result.put("userName", jwt.getClaim("userName").asString());
            result.put("userAccount", jwt.getClaim("userAccount").asString());
            result.put("userType", jwt.getClaim("userType").asInt());
            result.put("userTenantIds", jwt.getClaim("userTenantIds").asString());
            result.put("userRoleIds", jwt.getClaim("userRoleIds").asString());
            result.put("userDeptIds", jwt.getClaim("userDeptIds").asString());
            result.put("userPostIds", jwt.getClaim("userPostIds").asString());
            return result;
        } catch (JWTVerificationException exception) {
            throw new JWTVerificationException("登录过期,请重新登录");
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }
}

4、然后在拦截器中进行控制,可参考我之前的文章
集成token

注意这个版本的需要把鉴权替换成我这篇文章的

相关推荐
江江爱编程几秒前
java零基础保姆级教学01
java·开发语言
9624562 分钟前
餐饮 SaaS 优惠券系统架构演进(三):优惠计算引擎——商品级计价、冲突策略与优惠分摊
java·数据库·spring boot
vx_Biye_Design5 分钟前
expressDeepSeek社团咨询助手的学生社团管理系统60746-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·python·课程设计·express
vx_Biye_Design19 分钟前
springboot宠物领养与救助平台64334-计算机课程设计、毕业设计
java·vue.js·spring boot·后端·mysql·课程设计·宠物
泡茶喝茶写代码21 分钟前
A股量化数据工程:从 REST 接口到策略信号(第 5 篇):板块成分股映射与对齐
java·python·股票数据api·股票数据·股票数据api接口·股票api数据接口·股票量化数据接口
vx_Biye_Design22 分钟前
django就业信息推荐系统61953-计算机课程设计、毕业设计
java·vue.js·spring boot·python·架构·django·课程设计
零基础12332 分钟前
VoiceStudio 开源项目深度解析:特性、对比与实战测试
人工智能·经验分享·python·开源
2601_9628857236 分钟前
如何用 Python 做均线粘合选股?(多头发散前的变盘候选)
开发语言·python
zhangzeyuaaa37 分钟前
Ruby 方法参数完全指南:默认值、可变参数与关键字参数
前端·python·ruby
知守观38 分钟前
HTML 转 PDF 方案实战:iTextPDF 与 wkhtmltopdf 踩坑复盘,附 Flying Saucer / openhtmltopdf 选型对比
java·后端