json web tocken java,Json Web Token 的Java使用 (JJWT)

JWT是什么我就不做介绍了,在这只说一下JWT的开源的第三方JJWT的初步使用

话不多说,上代码

JwtUtil.class

public class JwtUtil

{

private String jianshu;

/**

* 由字符串生成加密key

* @return

*/

public SecretKey generalKey(){

String stringKey = jianshu+Constant.JWT_SECRET;

byte[] encodedKey = Base64.decodeBase64(stringKey);

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

return key;

}

/**

* 创建jwt

* @param id

* @param subject

* @param ttlMillis

* @return

* @throws Exception

*/

public String createJWT(String id, String subject, long ttlMillis) throws Exception {

SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

long nowMillis = System.currentTimeMillis();

Date now = new Date(nowMillis);

SecretKey key = generalKey();

JwtBuilder builder = Jwts.builder()

.setId(id)

.setIssuedAt(now)

.setSubject(subject)

.signWith(signatureAlgorithm, key);

if (ttlMillis >= 0) {

long expMillis = nowMillis + ttlMillis;

Date exp = new Date(expMillis);

builder.setExpiration(exp);

}

return builder.compact();

}

/**

* 解密jwt

* @param jwt

* @return

* @throws Exception

*/

public Claims parseJWT(String jwt) throws Exception{

SecretKey key = generalKey();

Claims claims = Jwts.parser()

.setSigningKey(key)

.parseClaimsJws(jwt).getBody();

return claims;

}

/**

* 生成subject信息

* @param user

* @return

*/

public static String generalSubject(t_user user){

JSONObject jo = new JSONObject();

jo.put("userId", user.getId());

jo.put("mobile", user.getMobile());

return jo.toJSONString();

}

}

Constant.class

public class Constant

{

/**

* jwt

*

*/

public static final String JWT_ID = "jwt";

public static final String JWT_SECRET = "hong1mu2zhi3ruan4jian5";

public static final int JWT_TTL = 60*60*1000; //millisecond

public static final int JWT_REFRESH_INTERVAL = 55*60*1000; //millisecond

public static final int JWT_REFRESH_TTL = 12*60*60*1000; //millisecond

}

在这只是JJWT的最基本的实现,后续会继续完善.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值