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;
}
}
- 后台管理系统联调