/* 采用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(); } }