package com.miaxis.util;
import com.miaxis.user.entity.User;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.logging.log4j.util.Strings;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* <p> @Title TokenUtil
* <p> @Description Token 工具类
*/
public class TokenUtil {
public static final String JWT_SECRET_KEY = "testjwt";
/**
* 创建Token
*
* @param user 用户实体
* @return Token
*/
public static String createToken(User user) {
// 登录成功后生成JWT
// JWT的header部分,该map可以是空的,因为有默认值{"alg":HS256,"typ":"JWT"}
Map<String, Object> map = new HashMap<>();
// 30分钟过期时间
Calendar instance = Calendar.getInstance();
instance.add(Calendar.MINUTE,30);
return JWT.create()
// 添加头部
.withHeader(map)
// 添加payload
.withClaim("userId",user.getId())
.withClaim("username",user.getUsername())
.withClaim("email",user.getEmail())
// 设置过期时间
.withExpiresAt(instance.getTime())
// 设置签名 密钥
.sign(Algorithm.HMAC256(JWT_SECRET_KEY));
}
/**
* 检查Token是否有效
*
* @param token Token
* @return 是否有效
*/
public static boolean isValid(String token) {
if (Strings.isNotBlank(token)) {
try {
//创建验证对象,这里使用的加密算法和密钥必须与生成TOKEN时的相同否则无法验证
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JWT_SECRET_KEY)).build();
//验证JWT
DecodedJWT decodedJwt = jwtVerifier.verify(token);
return new Date().before(decodedJwt.getExpiresAt());
} catch (Exception e) {
return false;
}
} else {
return false;
}
}
/**
* 检查Token所有Claims
*
* @param token Token
* @return Claims
*/
public static Map<String, Object> getClaims(String token) {
if (isValid(token)) {
//创建验证对象,这里使用的加密算法和密钥必须与生成TOKEN时的相同否则无法验证
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JWT_SECRET_KEY)).build();
//验证JWT
DecodedJWT decodedJwt = jwtVerifier.verify(token);
//获取JWT中的数据,注意数据类型一定要与添加进去的数据类型一致,否则取不到数据
Map<String, Object> map = new HashMap<>();
map.put("userId", decodedJwt.getClaim("userId").asInt());
map.put("username", decodedJwt.getClaim("username").asString());
map.put("email", decodedJwt.getClaim("email").asString());
map.put("expire", decodedJwt.getExpiresAt());
return map;
} else {
throw new RuntimeException("Token验证失败,请重新登录");
}
}
}

mickey0380
- 粉丝: 2452
最新资源
- Google 机器学习入门视频的中文字幕翻译及示例代码
- 【能源效率模糊柔性作业车间调度】基于双种群进化算法的模糊完工时间和能耗优化系统设计(含详细代码及解释)
- A176基于springboot+vue的扶贫众筹网(完整前后端代码+sql脚本+开发文档+全套软件)
- 2025年新版医院感染知识试题(含答案).docx
- 2025年新版医院感染知识试题(附含答案).docx
- 2025年新生儿科院感培训试题(附含答案).docx
- 2025年信息技术学业水平全考试测试题与答案.docx
- 2025年信息技术学业水平全考试测试题及答案.docx
- 2025年新生儿科院感培训试题(含答案).docx
- 2025年消防安全培训考试题库与解析答案.docx
- 2025年消防安全培训考试题库及解析答案.docx
- 电机控制基于移动水平估计(MHE)的永磁同步电机(PMSM)无传感器驱动系统设计与优化(含详细代码及解释)
- 2025年信息技术中考练习系统必考试题库与答案.docx
- 2025年新媒体运营专业考试必考试题及答案.docx
- 2025年新生儿护理常规试题(附含答案).docx
- 2025年消毒供应中心理论试题(附答案).docx
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈


