java jwt制作token登陆验证

/**
 * 使用jwt创建token
 * @param id 存储id
 * @param subject 存储内容
 * @param ttlMillis  超时时间
 * @return
 * @throws Exception
 */
public String createJWT(String id, String subject, long ttlMillis) throws Exception {
     //从枚举类获取HS256加密我们的key
        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();
    }
/**
 * 由字符串生成加密key
 * @return
 */
public SecretKey generalKey(){
  //加密串
    String stringKey = demo+7786df7fc3a34e26a61c034d5ec8245d;
    byte[] encodedKey = Base64.decodeBase64(stringKey.getBytes());
    SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");

    return key;
}
 
/**
 * 解密jwt
 * @param jwt
 * @return
 * @throws Exception
 */
public Claims parseJWT(String jwt) {
    SecretKey key = generalKey();
    Claims claims = Jwts.parser()
            .setSigningKey(key)
            .parseClaimsJws(jwt).getBody();
    return claims;
}
 

解密完毕后使用

String json = claims.getSubject();即可获取到加密存入的subject的值
关于jwt生成token与解码获取值的代码展示到这,如有错误请指出
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值