zoukankan      html  css  js  c++  java
  • Jwt Token 令牌

    /*
    采用JWT的生成TOKEN,及APP登录Token的生成和解析
     */
    public class JwtTokenUtil {
        /**
         * token秘钥
         */
        public static final String SECRET = "1234567890";
        private static final String key = "user_code";
    
        /**
         * JWT生成Token.
         * JWT构成: header, payload, signature
         * @param userNo 登录成功后用户no, 参数no不可传空
         */
        @Validated
        public static String createToken(@NotBlank String userNo) throws Exception {
            Date iatDate = new Date();
            // expire time
            Calendar nowTime = Calendar.getInstance();
            nowTime.add(Calendar.DATE, 10);
            Date expiresDate = nowTime.getTime();
    
            // header Map
            Map<String, Object> map = new HashMap<>();
            map.put("alg", "HS256");
            map.put("typ", "JWT");
    
            // build token
            // param backups {iss:Service, aud:APP}
            String token = JWT.create().withHeader(map) // header
                    .withClaim("iss", "Service") // payload
                    .withClaim("aud", "APP")
                    .withClaim(key, userNo)
                    .withIssuedAt(iatDate) // sign time
                    .withExpiresAt(expiresDate) // expire time
                    .sign(Algorithm.HMAC256(SECRET)); // signature
    
            return token;
        }
    
        /**
         * 解密Token
         * @param token
         * @return
         * @throws Exception
         */
        private static Map<String, Claim> verifyToken(String token) {
            DecodedJWT jwt = null;
            try {
                JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
                jwt = verifier.verify(token);
            } catch (Exception e) {
                // e.printStackTrace();
                // token 校验失败, 抛出Token验证非法异常
                throw new BusinessException("token 验证失败");
            }
            return jwt.getClaims();
        }
    
        /**
         * 根据Token获取user_no
         * @param token
         * @return user_No
         */
        public static String getAppUID(String token) {
            Map<String, Claim> claims = verifyToken(token);
            Claim user_id_claim = claims.get(key);
            if (null == user_id_claim || StringUtils.isBlank(user_id_claim.asString())) {
                // token 校验失败, 抛出Token验证非法异常
                throw new BusinessException("token 异常");
            }
            return user_id_claim.asString();
        }
    }
  • 相关阅读:
    操作系统的发展史
    多线程的些许理解(平台x86,具体考虑linux,windows)
    C++ 11 智能指针
    C++虚函数和纯虚函数
    Qt之excel 操作使用说明
    查找之二叉排序树
    图的一些总结
    树的一些总结
    直接插入排序
    冒泡和选择排序
  • 原文地址:https://www.cnblogs.com/jonney-wang/p/10930312.html
Copyright © 2011-2022 走看看