HMAC256 Token

  1. 依赖包:
<dependency>
  <groupId>com.auth0</groupId>
  <artifactId>java-jwt</artifactId>
  <version>3.3.0</version>
</dependency>

使用

    Algorithm.HMAC256(uerPassword)  使用HMAC256加密算法,生成签名。

    具体如下:

  public static String sign(String username, Integer role, Integer userId, String secret, long expireTimeInMilliSeconds) {
    try {
//设置过期时间:获取当前时间+过期时间(毫秒)
      Date date = new Date(System.currentTimeMillis() + expireTimeInMilliSeconds);
//设置签名的加密算法:HMAC256
      Algorithm algorithm = Algorithm.HMAC256(secret);
      // 附带username信息
      return JWT.create().withClaim("username", username).withClaim("role", role).withClaim("uerId", userId).withExpiresAt(date).sign(algorithm);
    } catch (UnsupportedEncodingException e) {
      return null;
    }
  }

 自然生成token,token是合法用户的有效令牌,那么该怎么解密该令牌呢?以下是方法

  1. 主要解密方法:
DecodedJWT jwt = JWT.decode(token);

完整的代码:
public static Integer getUserId(String token) {
    try {
      DecodedJWT jwt = JWT.decode(token);
      return jwt.getClaim("userId").asInt();
    } catch (JWTDecodeException e) {
      return null;
    }
  }
注意,此jwt.getClaim("userId").asInt(); userId就是在前面生成token的方法中的 userId,注意字段的对应
JWT.create()
.withClaim("username", username)
.withClaim("role", role)
.withClaim("uerId", userId)
.withExpiresAt(date)
.sign(algorithm); 

  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值