SpringBoot integration jjwt and use
1.Introduce jwt dependencies
(Take jjwt as an example here. For other jwt products, please refer to the jwt official website)
<dependency> <groupId></groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
2. Add configuration to spring's startup class
jwt: # Signature, random settings signature: IU$S&39S%57!kYs@Nc # Expiration time (minutes) destroy_time: 30
3. Complete jwt tool class code
Copy and use
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * @author Salong * @date 2023/11/16 17:27 * @Email:salong0503@ jwt toolkit based on jjwt package */ @Component public class JjwtUtil { @Value("${}") public void setSignature(String signature) { = signature; } @Value("${jwt.destroy_time}") public void setDestroyTime(int destroyTime) { = destroyTime; } /** * signature signature */ private static String signature; /** * jwt failure time (minutes) */ private static int destroyTime; public static void main(String[] args) { = "IU$S&39S%57!kYs@Nc"; = 30; HashMap<String, Object> map = new HashMap<>(); ("name", "Zhang San"); ("age", 14); String token = getToken(map); ("token:" + token); //Note: The token obtained above can be used to parse content on content analysis platforms such as https:///tools/, etc. // Therefore, sensitive information cannot be placed. If sensitive information is to be placed, the issued token needs additional encryption and decryption to be able to be circulated on the Internet Claims claims = parseToken(token); ((claims)); } public static String getToken(HashMap<String, Object> map) { JwtBuilder jwtBuilder = () //The only id .setId(().toString()) //Todo accepts users (user id is generally stored, and the map parameter provided needs to be given this parameter) .setSubject("Salong") //Issuance time .setIssuedAt(new Date()) //Set the failure time (1 minute invalid) .setExpiration(new Date(() + 60L * 1000 * destroyTime)) //Signature algorithm and secret key .signWith(SignatureAlgorithm.HS256, signature) .addClaims(map); return (); } public static Claims parseToken(String token) { //Analyze token return (Claims) () .setSigningKey(signature) .parse(token) .getBody(); } }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.