zoukankan      html  css  js  c++  java
  • 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); 

      

  • 相关阅读:
    UVA 1025 A Spy in the Metro DP水题
    ZOJ 3814 Sawtooth Puzzle BFS
    ZOJ 3816 Generalized Palindromic Number
    UVA 10859 Placing Lampposts 树形DP
    UVA 11825 Hackers' Crackdown 状压DP
    POJ 2887 Big String 线段树 离线处理
    POJ 1635 Subway tree systems Hash法判断有根树是否同构
    BZOJ 3110 k大数查询 & 树套树
    sdoi 2009 & 状态压缩
    来自于2016.2.24的flag
  • 原文地址:https://www.cnblogs.com/qq1141100952com/p/10681475.html
Copyright © 2011-2022 走看看