Jwt Token 令牌
2024-10-21 13:06:48
/*
采用JWT的生成TOKEN,及APP登录Token的生成和解析
*/
public class JwtTokenUtil {
/**
* token秘钥
*/
public static final String SECRET = "1234567890";
private static final String key = "user_code"; /**
* JWT生成Token.
* JWT构成: header, payload, signature
* @param userNo 登录成功后用户no, 参数no不可传空
*/
@Validated
public static String createToken(@NotBlank String userNo) throws Exception {
Date iatDate = new Date();
// expire time
Calendar nowTime = Calendar.getInstance();
nowTime.add(Calendar.DATE, 10);
Date expiresDate = nowTime.getTime(); // header Map
Map<String, Object> map = new HashMap<>();
map.put("alg", "HS256");
map.put("typ", "JWT"); // build token
// param backups {iss:Service, aud:APP}
String token = JWT.create().withHeader(map) // header
.withClaim("iss", "Service") // payload
.withClaim("aud", "APP")
.withClaim(key, userNo)
.withIssuedAt(iatDate) // sign time
.withExpiresAt(expiresDate) // expire time
.sign(Algorithm.HMAC256(SECRET)); // signature return token;
} /**
* 解密Token
* @param token
* @return
* @throws Exception
*/
private static Map<String, Claim> verifyToken(String token) {
DecodedJWT jwt = null;
try {
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
jwt = verifier.verify(token);
} catch (Exception e) {
// e.printStackTrace();
// token 校验失败, 抛出Token验证非法异常
throw new BusinessException("token 验证失败");
}
return jwt.getClaims();
} /**
* 根据Token获取user_no
* @param token
* @return user_No
*/
public static String getAppUID(String token) {
Map<String, Claim> claims = verifyToken(token);
Claim user_id_claim = claims.get(key);
if (null == user_id_claim || StringUtils.isBlank(user_id_claim.asString())) {
// token 校验失败, 抛出Token验证非法异常
throw new BusinessException("token 异常");
}
return user_id_claim.asString();
}
}
最新文章
- http 各个状态码及对应的java 编程
- python 笔记1:安装python;eclipse中安装配置pydev
- 【Ubuntu日常技巧】VirtualBox多网卡路由配置,保障虚拟机连接上外网
- install kinect driver for ARM---38
- Hibernate O/R Mapping模拟
- Oracle INV - SO line backorder API
- [转载] ubuntu Authentication failure
- plupload上传控件错误exec(this.uid, component, action, args)
- Linux---More命令 初级实现
- uoj164. 【清华集训2015】V 统计
- 解决ios上微信无法捕获返回键按钮事件的问题
- storage theory
- Ubuntu中Qt新建窗体提示lGL错误
- 关于批量插入数据之我见(100万级别的数据,mysql) (转)
- C++/CLI泛型应用
- QQ的ldw值计算方法
- django基础 -- 4. 模板语言 过滤器 模板继承 FBV 和CBV 装饰器 组件
- Go parameter passing
- Git 使用SSH密钥操作
- mysql查询表基本操作