当前位置: 首页 > news >正文

spring boot jwt生成token

1、引入jwt依赖

<!--jwt的依赖-->
<dependency>
    <groupId>com.auth0</groupId>
    <artifactId>java-jwt</artifactId>
    <version>3.18.3</version>
</dependency>

2、创建TokenUtils工具类

package com.pn.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.pn.entity.CurrentUser;
import com.pn.entity.User;    //实体类
import com.pn.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.Date;

/**
 * token工具类
 */
@Component
public class TokenUtils {

    //注入redis模板
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

     Redis  0库
   // @Autowired
   // @Qualifier("reactiveRedisTemplateDb0")
   // private ReactiveRedisTemplate<String, Object> redis;

    //注入配置文件中的warehouse.expire-time属性 -- token的过期时间
    @Value("${warehouse.expire-time}")
    private Long expireTime;

    /**
     * 常量:
     */
    //token中存放用户id对应的名字
    private static final String CLAIM_NAME_USERID = "CLAIM_NAME_USERID";
    //token中存放用户名对应的名字
    private static final String CLAIM_NAME_USERCODE = "CLAIM_NAME_USERCODE";
    //token中存放用户真实姓名对应的名字
    private static final String CLAIM_NAME_USERNAME = "CLAIM_NAME_USERNAME";

    // 真正的生成的jwt token的方法
    private String sign(User user) {
        String token = JWT.create()
                .withClaim(CLAIM_NAME_USERID, user.getUserId())
                .withClaim(CLAIM_NAME_USERCODE, user.getUserCode())
                .withClaim(CLAIM_NAME_USERNAME, user.getUserName())
                .withIssuedAt(new Date())//发行时间
                .withExpiresAt(new Date(System.currentTimeMillis() + (expireTime * 1000L)))//有效时间
                .sign(Algorithm.HMAC256(user.getUserPwd()));//指定签名
        return token;
    }

    /**
     * 方法一,jwt生成的 token存Redis,用Redis判断是否存在
     * 将当前用户信息以用户密码为密钥生成token的方法
     */
    public String loginSign(User user){
        //生成token
        String token = sign(user);
        //将token保存到redis中,并设置token在redis中的过期时间
        //stringRedisTemplate.opsForValue().set(token, token, Duration.ofSeconds(28800)).subscribe();
        stringRedisTemplate.opsForValue().set(token, token, expireTime);
        return token;
    }

    /**
     * 方法二,解析前端jwt生成的token进行校验
     * 创建CurrentUser实体类接收
     * 从客户端归还的token中获取用户信息的方法
     */
    public CurrentUser getCurrentUser(String token) {
        if(StringUtils.isEmpty(token)){
            throw new BusinessException("令牌为空,请登录!");
        }
        //对token进行解码,获取解码后的token
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = JWT.decode(token);
        } catch (JWTDecodeException e) {
            throw new BusinessException("令牌格式错误,请登录!");
        }
        //从解码后的token中获取用户信息并封装到CurrentUser对象中返回
        int userId = decodedJWT.getClaim(CLAIM_NAME_USERID).asInt();//用户账号id
        String userCode = decodedJWT.getClaim(CLAIM_NAME_USERCODE).asString();//用户账号
        String userName = decodedJWT.getClaim(CLAIM_NAME_USERNAME).asString();//用户姓名
        if(StringUtils.isEmpty(userCode) || StringUtils.isEmpty(userName)){
            throw new BusinessException("令牌缺失用户信息,请登录!");
        }
        return new CurrentUser(userId, userCode, userName);
    }

}

3、使用

//  注入token对象
    @Autowired
    private TokenUtils tokenUtils;

    @RequestMapping("/login")
    public String login(@RequestBody LoginUser loginUser) {

        // 生成token
        String token = tokenUtils.loginSign("传入实体类");
        System.out.println(token);
        return token ;
        
    }


文章转载自:

http://h21JgQTN.LLyjx.cn
http://bTMTtF4F.LLyjx.cn
http://XIcGyqgi.LLyjx.cn
http://bfaAT4Gb.LLyjx.cn
http://6qxBJewv.LLyjx.cn
http://Rk29KI1d.LLyjx.cn
http://qCnAR1u7.LLyjx.cn
http://X2DMGsEy.LLyjx.cn
http://11otrXSa.LLyjx.cn
http://UeoTGkH7.LLyjx.cn
http://Glx6G55A.LLyjx.cn
http://psy0FOfR.LLyjx.cn
http://URYTXrJZ.LLyjx.cn
http://6hRKwu31.LLyjx.cn
http://GHzKKjQ7.LLyjx.cn
http://LX6oDWck.LLyjx.cn
http://zeWGHVOW.LLyjx.cn
http://caNwHKLu.LLyjx.cn
http://Jwm9p7p0.LLyjx.cn
http://KIZDhdYo.LLyjx.cn
http://0yOpzXYf.LLyjx.cn
http://HzdN8ZQp.LLyjx.cn
http://jd261cGx.LLyjx.cn
http://m4uuIv4b.LLyjx.cn
http://GF7UkDqp.LLyjx.cn
http://HzakCgZx.LLyjx.cn
http://4TDt2gQj.LLyjx.cn
http://stu03a5k.LLyjx.cn
http://jDJyCFol.LLyjx.cn
http://H6kaeQfd.LLyjx.cn
http://www.dtcms.com/a/89886.html

相关文章:

  • OpenBMC:BmcWeb添加路由5 设置handler函数
  • 网络华为HCIA+HCIP 动态路由协议
  • 大模型训练 | 智能体知识库 资源收集之心理咨询问答数据集
  • Sqoop-试题
  • mysql的学习
  • C语言的内存模型 (堆区,栈区,静态区,常量区,代码区 )概念讲解
  • 互感器制作流程
  • 什么是独立服务器?为什么选择它?
  • 数据分析中,文件解析库解析内容样式调整
  • 一个数组分为两个sum相等的数组
  • 正弦函数的连续傅里叶变换正弦序列的DTFT
  • FPGA助力智能机器人应用
  • 小样本学习(Few-Shot Learning)基本概念 VS 监督学习
  • docker-操作实战
  • 为什么递归用栈?动态分配用堆?
  • 网络编程的概念&作用
  • vscode ssh连接ubantu显示管道不存在,VMware Virtual Ethernet Adapter for VMnet8不存在
  • 6.3 模拟专题:LeetCode 6. Z 字形变换
  • Vue3 知识点总结
  • 在 PostgreSQL 中设置调试环境以更好地理解 OpenSSL API
  • DeepSeek 助力 Vue3 开发:打造丝滑的表格(Table)之添加行拖拽排序功能示例1,TableView16_01.vue 基础行拖拽排序示例
  • cnn中的dropout技术
  • 如何在jupyter notebook中使用django框架
  • Linux 配置时间服务器
  • 企业级全栈开发终极指南:Spring Boot+Vue3+Kubernetes实战,从0到上线高并发系统
  • 禾赛盈利了,但激光雷达没有胜利
  • 基于web的家政服务网站
  • JPA实体类注解缺失异常全解:从报错到防御!!!
  • 【CF】Day15——Codeforces Round 1012 (Div. 2) CD
  • 【微服务架构】故障转移策略的理解及手写实现