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();
        }
    }
  • 相关阅读:
    mysql CREATE USER
    ConvertHelper 通用类
    自定义属性
    为什么建议使用你LocalDateTime,而不是Date?
    使用IDEA插件Alibaba Cloud Toolkit工具一键部署本地应用到ECS服务器
    IDEA-SpringBoot项目设置热部署
    CentOS7中MySQL跨机器数据迁移
    Centos7 使用YUM安装Mariadb
    Linux下svn服务器迁移
    java dateutil工具类Date.add()
  • 原文地址:https://www.cnblogs.com/jonney-wang/p/10930312.html
Copyright © 2011-2022 走看看