JWT,JSON Web Token
在 JWT.IO 查看关于 JWT 的一些介绍,以及查找 JWT 各种语言都有哪些实现库
中文博客里,阮一峰的一篇博客还是比较易懂的:JSON Web Token 入门教程 。
JWT.IO 推荐了 6 个 Java 实现库:Libraries for Token Signing/Verification。
经过使用,感觉 Java JWT 还是很好用的。这里记录以下使用这个库的一些小测试,以后就不用到处找了。
Java JWT 的官方 GitHub:Java JWT
Maven 引入:
1 2 3 4 5
| <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.18.3</version> </dependency>
|
此库需要 Java 8 或更高版本。支持 Java 7 的最后一个版本是 3.11.0。
以下是测试代码(测试工具是 JUnit 4.12):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
| import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTVerificationException; import com.auth0.jwt.interfaces.DecodedJWT; import org.junit.Test;
import java.util.Date;
public class JwtTest {
@Test public void generate() { Algorithm algorithm = Algorithm.HMAC256("secret"); final int duration = 24 * 60 * 60 * 1000; String token = JWT.create() .withIssuer("YGQ Issuer") .withSubject("主题是测试") .withClaim("birthday", "1997-10-01") .withExpiresAt(new Date(System.currentTimeMillis() + duration)) .sign(algorithm); System.out.println(token); }
@Test public void parse() { String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" + ".eyJiaXJ0aGRheSI6IjE5OTctMTAtMDEiLCJzdWIiOiLkuLvpopjmmK_mtYvor5UiLCJpc3MiOiJZR1EgSXNzdWVyIiwiZXhwIjoxNjQ1MDA3Mzg4fQ.1IGrhgA9gfyp6GUXFRfOZPpgIMxZNSxelkBpRFrC6T8"; DecodedJWT decodedJWT = JWT.decode(token); System.out.println(decodedJWT.getExpiresAt()); System.out.println(decodedJWT.getClaim("birthday")); }
@Test public void verify() { String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" + ".eyJiaXJ0aGRheSI6IjE5OTctMTAtMDEiLCJzdWIiOiLkuLvpopjmmK_mtYvor5UiLCJpc3MiOiJZR1EgSXNzdWVyIiwiZXhwIjoxNjQ1MDA3Mzg4fQ.1IGrhgA9gfyp6GUXFRfOZPpgIMxZNSxelkBpRFrC6T8"; Algorithm algorithm = Algorithm.HMAC256("secret"); JWTVerifier jwtVerifier = JWT.require(algorithm) .withIssuer("YGQ Issuer") .withClaim("birthday", "1999-10-01") .build(); try { DecodedJWT decodedJWT = jwtVerifier.verify(token); System.out.println(decodedJWT.getHeader()); System.out.println(decodedJWT.getPayload()); System.out.println(decodedJWT.getSignature()); System.out.println(decodedJWT.getExpiresAt()); } catch (JWTVerificationException e) { System.out.println(e.getMessage()); } } }
|