版本随意,开心就好
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
package code9xs.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.interfaces.DecodedJWT; import sun.misc.Cleaner; import java.io.UnsupportedEncodingException; import java.util.Calendar; import java.util.HashMap; import java.util.Map; public class JwtUtil { static final String sign = "this is an jwt signature"; public static String ctrateJwt(String username, String id){ // 设置过期时间 Calendar instance = Calendar.getInstance(); instance.add(Calendar.DATE, 7); // 设置 header // Map<String, String> header = new HashMap<>(); // header.put("alg", "HS256"); // header.put("typ", "JWT"); // 生成令牌 String token = JWT.create() // .withHeader() // 设置 header .withClaim("username", username) // 设置用户名 payload 自定义部分 .withClaim("id", id) // 设置id payload 自定义部分 .withExpiresAt(instance.getTime()) // 设置过期时间 .sign(Algorithm.HMAC256(sign)); // 设置签名, 需要将签名使用HMAC256加密后传入 System.out.println(token); return token; } public static Boolean verify(String token) { // 加密签名 Algorithm algorithm = Algorithm.HMAC256(sign); // 构建 JWTVerifier verifier = JWT.require(algorithm).build(); // 验证token DecodedJWT jwt = verifier.verify(token); String username = jwt.getClaim("username").asString(); String id = jwt.getClaim("id").asString(); System.out.println(String.format("this user is %s", username)); System.out.println(String.format("this user's ID is %s", id)); return true; } public static void main(String[] args) { // String token = ctrateJwt("su.haodong", "6407003302"); verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjY0MDcwMDMzMDIiLCJleHAiOjE2NjEzNDk2NjYsInVzZXJuYW1lIjoic3UuaGFvZG9uZyJ9.aW_Nd9CXiTVLHBrK2XzNk670sPWh662qpa-v5VvEzV0"); } }