【mybatis-plus问题集锦系列】jjwt最新版本0.12.5的使用方法及报错解决

jjwt网上大部分都是版本0.9.1的使用方法,最新版本已经更新到0.12.5了,还继续用之前的写法就会显示很多过时的方法,还有很多报错,旧版写法参考springboot中会话技术方案cookie/session/jwt这篇文章

最新版本号

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.12.5</version>
</dependency>

报错问题

  • jwt报错key太短了解决方法:

io.jsonwebtoken.security.WeakKeyException: The signing key’s size is 40 bits which is not secure enough for the HS256 algorithm. The JWT JWA Specification (RFC 7518, Section 3.2) states that keys used with HS256 MUST have a size >= 256 bits (the key size must be greater than or equal to the hash output size). Consider using the io.jsonwebtoken.security.Keys class’s ‘secretKeyFor(SignatureAlgorithm.HS256)’ method to create a key guaranteed to be secure enough for HS256. See https://tools.ietf.org/html/rfc7518#section-3.2 for more information.

  • 版本依赖
<dependency>
	<groupId>io.jsonwebtoken</groupId>
	<artifactId>jjwt</artifactId>
	<version>0.9.1</version>
</dependency>

在这里插入图片描述

在这里插入图片描述

  • 问题就是signWith里面的加密字符太短了,需要加大长度
    String key = "ddddddddddddddddddddddddddddddddddddddddddddgaofeng";
    String jwt ="eyJhbGciOiJIUzM4NCJ9.eyJuYW1lIjoiZ2FvZmVuZyIsImlkIjoxLCJleHAiOjE3MzYxNjMwMDR9.SdZciXONLp5k_c1ynQnRz30s7jvD8hvjPj2Qr-WE_R6vN3WB3jEMcr46tyMnVH0E";
    @Test
    void contextLoads() {
        System.out.println("test from 111");
    }

    @Test
    public void testJWT(){
        HashMap<String, Object> claims = new HashMap<>();
        claims.put("id",1);
        claims.put("name","gaofeng");

        SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
        String jwt = Jwts.builder()
                .signWith(secretKey)
                .claims(claims)
                .expiration(new Date(System.currentTimeMillis() + 3600 * 1000))
                .compact();
        System.out.println(jwt);
    }

在这里插入图片描述
官网解码地址
在这里插入图片描述

  • 解析jwt的方法
@Test
    public void parseJWT(){
        SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
        JwtParser jwtParser  = Jwts.parser().verifyWith(secretKey).build();
        Jws<Claims> jws = jwtParser.parseSignedClaims(jwt);
        Claims claims = jws.getPayload();
        System.out.println(claims);
    }

在这里插入图片描述
最新版的写法跟之前的0.9.1的写法大不一样,这个需要注意细节

  • 使用jwt实现登录返回token
package com.gaofeng.controller;

import com.gaofeng.pojo.Emp;
import com.gaofeng.pojo.Result;
import com.gaofeng.service.EmpService;
import com.gaofeng.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author gaofeng
 * @date 2025-01-06 - 18:56
 */
@Slf4j
@RestController
@RequestMapping("/sys")
public class LoginController {

    @Autowired
    private EmpService empService;

    @PostMapping("/login")
    public Result login(@RequestBody Emp emp){
        log.info("登录接口");
        Emp e = empService.login(emp);
        // 如果登录成功
        if(e != null){
            HashMap<String, Object> claims = new HashMap<>();
            claims.put("id",e.getId());
            claims.put("username",e.getUsername());
            claims.put("name",e.getName());
            String jwt = JwtUtils.createJwt(claims);
            return  Result.success(jwt);
        }
        return Result.error("用户名或密码错误");
    }
}
  • jwt方法封装
package com.gaofeng.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

/**
 * @author gaofeng
 * @date 2025-01-06 - 18:50
 */
public class JwtUtils {
    public static final String key = "ddddddddddddddddddddddddddddddddddddddddddddgaofeng";
    public static String createJwt(Map<String,Object> claims){
        SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
        String jwt = Jwts.builder()
                .signWith(secretKey)
                .claims(claims)
                .expiration(new Date(System.currentTimeMillis() + 3600 * 1000))
                .compact();
        return  jwt;
    }
    public static Claims parseJwt(String jwt){
        SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
        JwtParser jwtParser  = Jwts.parser().verifyWith(secretKey).build();
        Jws<Claims> jws = jwtParser.parseSignedClaims(jwt);
        Claims claims = jws.getPayload();
        System.out.println(claims);
        return claims;
    }
}

在这里插入图片描述
在这里插入图片描述

  • 后台管理系统联调请添加图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风清云淡_A

觉得有帮助的话可以给点鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值