Yesterday, I explained the introduction, application scenarios, advantages and matters needing attention of JWT. Today, I would like to introduce the specific use practice of JWT.

JJWT is the most complete algorithm supported by Java according to the class library supported by JWT official website. It is recommended to use JJWT. The website is as follows.

github.com/jwtk/jjwt

Here is how to use JJWT to achieve JWT token generation and decryption, mainly using SHA512 algorithm to demonstrate.

1. Import the JJWT maven package.

<dependency> <groupId> IO. Jsonwebtoken </groupId> <artifactId> JJWT </artifactId> <version>0.9.0</version> </dependency>Copy the code

Note: JJWT is dependent on Jackson 2.x, lower versions will report an error.

2. Create a JWTTest Test class.

3. Create a key.

The SHA512 algorithm is used here, so you need a key.

Key KEY = new SecretKeySpec("javastack".getBytes(),
            SignatureAlgorithm.HS512.getJcaName());
Copy the code

This generates a fixed key: Javastack

4. Generate JWT token.

The core code is as follows:

Map<String, Object> stringObjectMap = new HashMap<>();
stringObjectMap.put("type", "1");
String payload = "{\"user_id\":\"1341137\", \"expire_time\":\"2018-01-01 0:00:00\"}";
String compactJws = Jwts.builder().setHeader(stringObjectMap)
.setPayload(payload).signWith(SignatureAlgorithm.HS512, KEY).compact();

System.out.println("jwt key:" + new String(KEY.getEncoded()));
System.out.println("jwt payload:" + payload);
System.out.println("jwt encoded:" + compactJws);
Copy the code

Note: Header claims cannot be set, and payload cannot be set at the same time.

Output result:

jwt key:javastack jwt payload:{"user_id":"1341137", "expire_time":"2018-01-01 0:00:00"} jwt encoded:eyJ0eXBlIjoiMSIsImFsZyI6IkhTNTEyIn0.eyJ1c2VyX2lkIjoiMTM0MTEzNyIsICJleHBpcmVfdGltZSI6IjIwMTgtMDEtMDEgMDowMDowMCJ9 .cnyXRnwczgNcNYqV6TUY2MaMfk6vujsZltC8Q51l40dwYJg516oZcV4VDKOypPT8fD7AE63PIhfdm2ALVrfv5ACopy the code

5. Decrypt JWT token content.

The core code is as follows:

Jws<Claims> claimsJws = Jwts.parser().setSigningKey(KEY).parseClaimsJws(compactJws);
JwsHeader header = claimsJws.getHeader();
Claims body = claimsJws.getBody();

System.out.println("jwt header:" + header);
System.out.println("jwt body:" + body);
System.out.println("jwt body user-id:" + body.get("user_id", String.class));
Copy the code

Output result:

jwt header:{type=1, alg=HS512}
jwt body:{user_id=1341137, expire_time=2018-01-01 0:00:00}
jwt body user-id:1341137
Copy the code

Then use ciphertext to decrypt the debugger on the JWT website to see if it succeeds.

Decryption success, other algorithms use the same logic, so we can use JWT to achieve the secure transfer of data between different services.

Recommended reading

Dry goods: 2TB architect four-stage video tutorial

Interview: the most complete Java multithreaded interview questions and answers

Interview: the most comprehensive ali advanced Java interview questions in history

Interview: The most complete Spring interview questions in history

Tutorial: The most complete Spring Boot complete video tutorial

Books: 15 must-read books for advanced Java architects

Tools: Recommended an online creation flow chart, mind mapping software

Share Java dry goods, high concurrency programming, hot technology tutorials, microservices and distributed technology, architecture design, blockchain technology, artificial intelligence, big data, Java interview questions, and cutting-edge hot news.