java jwt token 使用_使用JWT实现Token认证

48304ba5e6f9fe08f3fa1abda7d326ab.png

public class JwtUtils {

/**

* 签发JWT

*

* @param id

* @param subject 可以是JSON数据 尽可能少

* @param ttlMillis

* @return String

*

*/

public static String createJWT(String id, String subject, long ttlMillis) {

SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

long nowMillis = System.currentTimeMillis();

Date now = new Date(nowMillis);

SecretKey secretKey = generalKey();

JwtBuilder builder = Jwts.builder().setId(id).setSubject(subject) // 主题

.setIssuer("user") // 签发者

.setIssuedAt(now) // 签发时间

.signWith(signatureAlgorithm, secretKey); // 签名算法以及密匙

if (ttlMillis >= 0) {

long expMillis = nowMillis + ttlMillis;

Date expDate = new Date(expMillis);

builder.setExpiration(expDate); // 过期时间

}

return builder.compact();

}

/**

* 验证JWT

*

* @param jwtStr

* @return

*/

public static CheckResult validateJWT(String jwtStr) {

CheckResult checkResult = new CheckResult();

Claims claims = null;

try {

claims = parseJWT(jwtStr);

checkResult.setSuccess(true);

checkResult.setClaims(claims);

} catch (ExpiredJwtException e) {

checkResult.setErrCode(SystemConstant.JWT_ERRCODE_EXPIRE);

checkResult.setSuccess(false);

} catch (SignatureException e) {

checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);

checkResult.setSuccess(false);

} catch (Exception e) {

checkResult.setErrCode(SystemConstant.JWT_ERRCODE_FAIL);

checkResult.setSuccess(false);

}

return checkResult;

}

public static SecretKey generalKey() {

byte[] encodedKey = Base64.decode(SystemConstant.JWT_SECERT);

SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");

return key;

}

/**

*

* 解析JWT字符串

*

* @param jwt

* @return

* @throws Exception

*/

public static Claims parseJWT(String jwt) throws Exception {

SecretKey secretKey = generalKey();

return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();

}

}

48304ba5e6f9fe08f3fa1abda7d326ab.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值