java-jwt
依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>4.4.0</version>
</dependency>
使用
JWTUtils.java
package org.example.myspringboot.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Calendar;
import java.util.Map;
public class JWTUtils {
// Token 预定义秘钥
private static final String SIGN = "SIGN";
/**
* 根据输入的键值对Map生成JWT令牌
* 可以创建一个带有过期时间及指定算法的签名令牌
*
* @param map 包含令牌payload数据的键值对,其中键是claim名称,值是claim值
* @return Token JWT令牌
*/
public static String createJWT(Map<String, String> map) {
// 获取当前时间
Calendar calendar = Calendar.getInstance();
// 设置Token过期时间
calendar.add(Calendar.DATE, 3);
// 创建Token构建器
JWTCreator.Builder builder = JWT.create();
// 设置payload中的claim,使用传入的Map进行遍历设置
map.forEach((k, v) -> {
builder.withClaim(k, v);
});
// 生成带有过期时间的token,并使用HMAC256算法进行签名
String token = builder.withExpiresAt(calendar.getTime())
.sign(Algorithm.HMAC256(SIGN));
return token;
}
// 校验token, 获取token中的信息
public static DecodedJWT verifyToken(String token) {
return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
}
}
LoginContorller.java
package org.example.myspringboot.accounts.controller;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import org.example.myspringboot.accounts.domain.Users;
import org.example.myspringboot.accounts.mapper.UsersMapper;
import org.example.myspringboot.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class LoginContorller {
@Autowired
private UsersMapper usersMapper;