“This is the 17th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
preface
I believe that many backend users first think of session-based or token-based authentication when doing permission authentication. When we do single sign-on for users of distributed site cluster, the authentication based on session and token has limitations, so is there a better way to deal with the authentication problem? Here we introduce JWT.
What is the JWT
JWT, short for JSON WEB TOKEN, is an open standard (RFC 7519) often used to securely transfer information between multiple parties. JWT is widely used in authorization and information interaction due to its high information security. The information encrypted by JWT is a tight, self-contained string of data.
JWT format
The JWT format is made up of three pieces of information separated by dots (.). Connection, the first part is header information, the second part is payload information, and the third part is visa information. The following string is a JWT string.
-
EyJhbGciOiJIUzI1NiJ9: Indicates the header information. The header information mainly includes the token type and algorithm.
-
EyJqdGkiOiIxIiwic3ViIjoiYWRtaW4xMjM0NTYiLCJpc3MiOiJ1c2VyIiwiaWF0IjoxNjM3MjM2NDI5LCJleHAiOjE2MzcyMzY0Mzl9: Carrier information is mainly encrypted data resource information.
-
T5pAMGV0Rx3C455f5c812yvqnC6UqwiTpALeo5EFvR8: visa information. The visa information is mainly used to verify that messages have not been tampered with during transmission.
It should be noted that sensitive information placed in header information and carrier information Z needs to be encrypted first.
eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoiYWRtaW4xMjM0NTYiLCJpc3MiOiJ1c2VyIiwiaWF0IjoxNjM3MjM2NDI5LCJleHAiOjE2MzcyMzY 0Mzl9.t5pAMGV0Rx3C455f5c812yvqnC6UqwiTpALeo5EFvR8Copy the code
Quick start
This will be based on Spring Boot to build a learning Mybatis_Plus optimistic lock Demo. The development environment is as follows:
RELEASE java-jwt 3.2.0 JJWT 0.7.0Copy the code
Rely on
This time, we need to add dependent packages related to JWT. The specific dependencies are as follows. If there are different versions, there may be compatibility problems with SpringBoot.
<dependency> <groupId>com.auth0</groupId> <artifactId> Java -jwt</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId> IO. Jsonwebtoken </groupId> <artifactId> JJWT </artifactId> <version>0.7.0</version> </dependency>Copy the code
Create JWT
SignatureAlgorithm indicates the algorithm name supported by the standard JWT SignatureAlgorithm defined in SignatureAlgorithm. It can be referenced directly. The specific algorithm name is as follows:
This time, the signature algorithm is SHA-256. First, specify the signature algorithm used by the JWT. Specific information is as follows:
SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
Copy the code
Set the SecretKey information again. Use Base64 to convert the secret key into a byte array. Create a SecretKeySpec key specification. AES encryption is used.
byte[] encodedKey = Base64.decode(JWT_SECERT);
SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
Copy the code
Let’s create a Jwt object based on JwtBuilder, which inherits from ClaimsMutator. Call jwts.Builder () and set the basic parameters of Builder to create JwtBuilder.
JwtBuilder builder = Jwts.builder().setId(id).setSubject(subject)
.setIssuer("juejin")
.setIssuedAt(now)
.setExpiration(expDate)
.signWith(signatureAlgorithm, secretKey);
builder.compact()
Copy the code
The information includes ID, subject encryption content, Issuer Issuer, IssuedAt issue time, Expiration time, signatureAlgorithm algorithm used by the signature, and secretKey. The JWT string is then created by calling the builder.compact() method. For example, using the string “digging for gold — more code, more digging for gold” produces a string of JWT information as follows:
eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoi5o6Y6YeR4oCU4oCU5Luj56CB5LiN5q2i77yM5o6Y6YeR5LiN5YGcIiwiaXNzIjoidXNlciIsIml hdCI6MTYzNzI0MjY0NywiZXhwIjoxNjM3MjQyNjU3fQ.mMkMRyxVTcOSZCDrR5cGvY6KcRPCVVQwETSyPQMSAQoCopy the code
Verify the JWT
The JWT information has been created above. Once we get the JWT information, how to verify and read the information contained in the JWT is introduced below. SecretKey is the secretKey information introduced above, and the obtaining method is similar to the above. JWT is the created JWT information. Then get Claims with getBody(),
Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
Copy the code
JWT Claims include user ID, ISS issuer information, SUB information, IAT issue time, and EXP expiration time. The above is the establishment and verification of the JWT creation process, which is verified in the Spring Boot project.
Test the JWT
Use for validation in a Spring Boot project. In this verification, two interfaces are used to invoke verification, one is to obtain JWT interface and the other is to verify JWT interface. The JWT information obtained is transmitted to the verification interface to see whether the information in JWT can be obtained. The interfaces are as follows:
@GetMapping("setJwt")
@ResponseBody
public String setJwt(String info){
return JwtUtils.createJWT("juejin",info,10000L);
}
@GetMapping("getJwt")
@ResponseBody
public String getJwt(String info)throws Exception{
return JwtUtils.validateJWT(info).getClaims().getSubject();
}
Copy the code
After starting the project, call the interface to get the JWT first, and you can see that the JWT has been obtained.
eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJqdWVqaW4iLCJzdWIiOiLmjpjph5HigJTigJTku6PnoIHkuI3mraLvvIzmjpjph5HkuI3lgZwiLCJpc3MiOiJ1c2V yIiwiaWF0IjoxNjM3MjQ1MTQwLCJleHAiOjE2MzcyNDUxNTB9.WKso2dPHEtSx_ItCCXmq2QjSDR6AIBzetKft4CJ8wNQCopy the code
Then verify the interface of JWT through the JWT call, and return “nuggets — the code does not stop, nuggets do not stop”, and the verification is successful.
conclusion
Ok, the above is a simple example of Spring Boot integration JWT, thank you for reading, I hope you like, if it is helpful to you, welcome to like favorites. If there are shortcomings, welcome comments and corrections. See you next time.
About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.