HMAC256 Token


依賴包:

<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,token是合法用戶的有效令牌,那么該怎么解密該令牌呢?以下是方法

主要解密方法:

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); 

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM