1、添加依赖
<!--jwt生成token--> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.1.0</version> </dependency>
2、代码,执行 main 看效果
package com.fbank.dis_common.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.InvalidClaimException; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.Claim; import com.auth0.jwt.interfaces.DecodedJWT; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; public class JwtToken { private static String SECRET = "secret key";//token加解密秘钥 private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 生成 Token * * @param userId * @return * @throws UnsupportedEncodingException */ public static String createToken(String userId) throws UnsupportedEncodingException { Calendar nowTime = Calendar.getInstance(); Calendar nowTime2 = Calendar.getInstance(); System.out.println("当前时间:" + sdf.format(nowTime.getTime())); nowTime2.add(Calendar.SECOND, 0);//指定token生效时间:当前时间0s后 Date effectTime = nowTime2.getTime(); nowTime.add(Calendar.MINUTE, 60);//指定token过期时间:当前时间60min后 Date maturityTime = nowTime.getTime(); System.out.println("token生效时间:" + sdf.format(effectTime)); System.out.println("token到期时间:" + sdf.format(maturityTime)); //JWT header Map header = new HashMap<>(); header.put("alg", "HS256"); header.put("typ", "JWT"); //JWT payload, 不能存放敏感数据 String token = JWT.create() .withHeader(header)//header .withClaim("name", "author")//payload .withClaim("age", 28) .withClaim("org", "cqfm") .withIssuedAt(new Date())//设置签发时间 .withExpiresAt(maturityTime)//设置过期时间 .withIssuer("银行")//签发者 .withSubject("用户")//jwt面向的用户 .withAudience("token使用者")//接收jwt的一方 .withNotBefore(effectTime)//定义token生效时间,在此之前都不可用 .withJWTId(userId)//jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击 .sign(Algorithm.HMAC256(SECRET));//秘钥加密 return token; } /** * 解析 Token * * @param token * @return * @throws UnsupportedEncodingException */ public static Map<String, Claim> verifyToken(String token) throws UnsupportedEncodingException { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();//秘钥解密 DecodedJWT jwt = null; try { jwt = verifier.verify(token); } catch (JWTVerificationException e) { e.printStackTrace(); if (e.getMessage().startsWith("The Token can't be used before")) { throw new InvalidClaimException("登录凭证暂未生效"); } if (e.getMessage().startsWith("The Token has expired on")) { throw new InvalidClaimException("登录凭证已过期,请重新登录"); } } return jwt.getClaims(); } public static void main(String[] args) throws UnsupportedEncodingException { String token = createToken("4557"); System.out.println("------生成token------\n" + token); Map<String, Claim> claims = verifyToken(token); System.out.println("------解析token------\n" + claims.toString()); //使用过期的token进行校验 String lastToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiLlr4zmsJHlrp0m5a-M6ZGr5a6d55So5oi3IiwiYXVkIjoidG9rZW7kvb_nlKjogIUiLCJuYmYiOjE1NDY5MzM1MjcsIm9yZyI6ImNxZm0iLCJuYW1lIjoiYXV0aG9yIGlzIGpqcCIsImlzcyI6IuWvjOawkemTtuihjCIsImV4cCI6MTU0NjkzNzEyNywiaWF0IjoxNTQ2OTMzNTI3LCJhZ2UiOjI4LCJqdGkiOiI0NTU3In0.u4jlhdZ-GUFm9HpvLe9QigM0gLmtD0gMdN5if_5p1wE"; Map<String, Claim> lastClaims = verifyToken(lastToken); Claim claim = lastClaims.get("sub"); String sub = claim.asString(); System.out.println(sub); System.out.println("------解析上个token------\n" + lastClaims.toString()); } }