common-module/utils/JwtUtils.java
cuijiawang ea58e018b4 init
2025-05-27 17:58:49 +08:00

114 lines
3.5 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.sgcc.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sgcc.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* JWT工具类
*
* @author zhaoyuanyuan
* @version 1.0.0
* @date 2024/06/27 14:47
*/
@Slf4j
public class JwtUtils {
/**
* JWT用户名
*/
private static final String USER_NAME = "admin";
/**
* token有效时间
*/
public static final int TOKEN_TIME_OUT = 1000 * 60 * 60;
/**
* 生成token
*
* @param user 用户信息
* @param key 用于签名加密的密钥
* @return {@code String }
* @author zhaoyuanyuan
* @date 2024/11/22 11:15
*/
public static String getToken(User user, String key) {
//获取jwt生成器
JWTCreator.Builder jwtBuilder = JWT.create();
//该生成器设置Header的参数为一个<String, Object>的Map,
Map<String, Object> headers = new HashMap<>();
//设置token的type为jwt
headers.put("typ", "jwt");
//表明加密的算法为HS256
headers.put("alg", "hs256");
//开始生成token
String token = jwtBuilder.withHeader(headers)
//接下来为设置PayLoad,Claim中的键值对可自定义
//设置用户ID
.withClaim("userId", user.getId())
//设置用户角色ID
.withClaim("roleId", user.getRoleId())
//token失效时间这里为一消失后失效
.withExpiresAt(new Date(System.currentTimeMillis() + TOKEN_TIME_OUT))
//设置该jwt的发行时间一般为当前系统时间
.withIssuedAt(new Date(System.currentTimeMillis()))
//token的发行者可自定义
.withIssuer(USER_NAME)
//进行签名,选择加密算法,以一个字符串密钥为参数
.sign(Algorithm.HMAC256(key));
log.info("-------------Token={}-------------", token);
return token;
}
/**
* 验证Token
*
* @param token 凭证
* @return boolean
* @author zhaoyuanyuan
* @date 2024/06/27 14:55
*/
public static boolean verify(String token) {
if (StringUtils.isBlank(token)) {
return false;
}
DecodedJWT decode = JWT.decode(token);
//若验证成功,就可获取其携带的信息进行其他操作
if (decode.getClaim("userId") == null) {
return false;
}
log.info("用户ID[{}]", decode.getClaim("userId").asInt());
log.info("用户角色ID[{}]", decode.getClaim("roleId").asInt());
//获取发送者,没有设置则为空
log.info("发送者[{}]", decode.getIssuer());
//获取过期时间
log.info("过期时间[{}]", String.valueOf(decode.getExpiresAt()));
//获取主题,没有设置则为空
log.info("主题[{}]", decode.getSubject());
return true;
}
/**
* 获取Token中的userId
*
* @param token 凭证
* @return {@code Integer }
* @author zhaoyuanyuan
* @date 2024/11/21 09:52
*/
public static Integer getUserId(String token) {
DecodedJWT decode = JWT.decode(token);
return decode.getClaim("userId").asInt();
}
}