JWT generates, parses tokens, and encapsulates tool classes

Time:2021-9-13

Json web token

  1. Import jjwt dependencies
 <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
  1. Generate a token, use the builder () method of tool class jwts, and return the token to the client after user authentication
public class CreateJwt {
    public static void main(String[] args) {
        Jwtbuilder jwtbuilder = jwts. Builder(). Setid ("88"). Setsubject ("Xiaobai")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "liang")
                //Add other non private content
                .claim("companyId","123456")
                . claim ("CompanyName", "Tencent");
        String token = jwtBuilder.compact();
        System.out.println(token);


    }
}
  1. The user sends a request with a token and parses the token
public class ParseJwt {
    public static void main(String[] args) {
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4OCIsInN1YiI6IuWwj-eZvSIsImlhdCI6MTU5MTE4ODgyNiwiY29tcGFueUlkIjoiMTIzNDU2IiwiY29tcGFueU5hbWUiOiLohb7orq8ifQ.jwJbTI_qCW365JgTtxeGz_jFXyFtQ4be-OCp5ezR4n8";
        Claims claims = Jwts.parser().setSigningKey("liang").parseClaimsJws(token).getBody();
        System.out.println(claims.getId());
        System.out.println(claims.getSubject());
        System.out.println(claims.getIssuedAt());
        //Parsing content in custom claim
        String companyId = (String) claims.get("companyId");
        String companyName = (String) claims.get("companyName");
        System.out.println(companyId);
        System.out.println(companyName);
    }
}
  1. Encapsulate generation and parsing into tool classes
package com.springboot.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

@Getter
@Setter
@ConfigurationProperties("jwt.config")
@Component
public class JwtUtils {
    //Signature private key
    private String key;
    //Signature validity time
    private long ttl;

    public String createJwtToken(String id, String name, Map<String,Object> map){
        //Set expiration time
        //Get current time
        long now=System.currentTimeMillis();
        //Current time + effective time = expiration time
        long exp=now+ttl;
        //Create jwtbuilder

        JwtBuilder jwtBuilder = Jwts.builder().setId(id).setSubject(name)
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, key);

        //Set clamis according to map
        jwtBuilder.setClaims(map);
        //Set expiration time
        jwtBuilder.setExpiration(new Date(exp));
        String token = jwtBuilder.compact();
        return token;
    }

    public Claims parseToken(String token){
        Claims claims = Jwts.parser().setSigningKey("liang").parseClaimsJws(token).getBody();
        return claims;
    }



}