1 What is JJWT

JJWT is a Java library that provides end-to-end JWT creation and validation. Always free and open source (Apache License, version 2.0), JJWT is easy to use and understand. It is designed as a smooth, architecture-centric interface that hides much of its complexity.

2 JJWT Quick Start

2.1 Token Creation

2.1.1 Maven introduces dependencies

<dependency>
	<groupId>io.jsonwebtoken</groupId>
	<artifactId>jjwt</artifactId>
	<version>0.9.1</version>
</dependency>
Copy the code

2.1.2 Creating the CreateJWT class to generate tokens

public class CreateJWT {
    public static void main(String[] args) {
        JwtBuilder jwtBuilder = Jwts.builder().setId("666777")
                .setSubject("Brain ablation")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "HelloWorld"); System.out.println(jwtBuilder.compact()); }}Copy the code
  • SetIssuedAt: used to set the issuing time.
  • SignWith: Used to set the signature key.

2.1.3 test

For the first time:

eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjY3NzciLCJzdWIiOiLohJHmtYbmtojono0iLCJpYXQiOjE2MDg4MDY3MDd9.v1SRR_xChK-K_T5GuHObQy5BnC OyZgGxBX-vrqBWwZgCopy the code

Run it again, and you’ll see that the result is different each time because our payload contains time:

eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjY3NzciLCJzdWIiOiLohJHmtYbmtojono0iLCJpYXQiOjE2MDg4MDY3ODV9.Da6HfKuSowFkWKmazLzFQSvkWz MPYNCEuNu12Q7e8mMCopy the code

2.2 Token Resolution

We have just created the token. In the Web application, this is done by the server and then sent to the client. The client needs to carry the token with it the next time it sends a request to the server (this is like holding a ticket). The server receiving the token should parse the information in the token (such as the user ID), query the database based on this information and return the corresponding result.

public class ParserJwtTest {

    public static void main(String[] args) {
        Claims claims = Jwts.parser().setSigningKey("HelloWorld")
                .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjY3NzciLCJzdWIiOiLohJHmtYbmtojono0iLCJpYXQiOjE2MDg4MDY3ODV9.Da6HfKuSowFkWKmazLzFQSvkW zMPYNCEuNu12Q7e8mM")
                .getBody();
        System.out.println("User ID:" + claims.getId());
        System.out.println("Username:" + claims.getSubject());
        System.out.println("Landing time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getIssuedAt())); }}Copy the code

Try tampering with the token or signature key, and you’ll find an error at runtime, so parsing the token is also validating the token.

For example, if the mM at the end of the token is removed, an error is reported:

2.3 Token Expiration Verification

There are many times when we don’t want to issue tokens to be permanent, so we can add an expiration date to the token.

public class CreateJWT {
    public static void main(String[] args) {
        JwtBuilder jwtBuilder = Jwts.builder().setId("666777")
                .setSubject("Brain ablation")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "HelloWorld")
                .setExpiration(new Date(new Date().getTime() + 60000)); System.out.println(jwtBuilder.compact()); }}Copy the code
  • SetExpiration method: Set the expiration time.

We modified the Jwt resolution class to add an expiration time:

public class ParserJwtTest {
    public static void main(String[] args) {
        Claims claims = Jwts.parser().setSigningKey("HelloWorld")
                .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjY3NzciLCJzdWIiOiLohJHmtYbmtojono0iLCJpYXQiOjE2MDg4MDk3NzksImV4cCI6MTYwODgwOTgzOX0.kA roSbh6Q5PzoA0iUxNtlpBVipvA6Zb2O3OcEFJkF88")
                .getBody();
        System.out.println("User ID:" + claims.getId());
        System.out.println("Username:" + claims.getSubject());
        System.out.println("Landing time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getIssuedAt()));
        System.out.println("Expiration Time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getExpiration())); }}Copy the code

Within 1 minute, the token can be used:

After 1 minute, expired and cause IO. Jsonwebtoken. ExpiredJwtException anomaly:

2.4 Custom Claims

Our example just stores the ID and subject information, but you can customize claims if you want to store more information (such as roles).

Add two more claims:

public class CreateJWT {
    public static void main(String[] args) {
        JwtBuilder jwtBuilder = Jwts.builder().setId("666777")
                .setSubject("Brain ablation")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "HelloWorld")
                .setExpiration(new Date(new Date().getTime() + 60000))
                .claim("sex"."man")
                .claim("age"."25"); System.out.println(jwtBuilder.compact()); }}Copy the code

Jwt parses the class and prints out gender and age:

public class ParserJwtTest {
    public static void main(String[] args) {
        Claims claims = Jwts.parser().setSigningKey("HelloWorld")
                .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjY3NzciLCJzdWIiOiLohJHmtYbmtojono0iLCJpYXQiOjE2MDg4MDk3NzksImV4cCI6MTYwODgwOTgzOX0.kA roSbh6Q5PzoA0iUxNtlpBVipvA6Zb2O3OcEFJkF88")
                .getBody();
        System.out.println("User ID:" + claims.getId());
        System.out.println("Username:" + claims.getSubject());
        System.out.println("Landing time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getIssuedAt()));
        System.out.println("Expiration Time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(claims.getExpiration()));
        System.out.println("Gender: + claims.get("sex"));
        System.out.println("Age:" + claims.get("age")); }}Copy the code

Results: