Json web token

  1. Import JJWT dependencies
<dependency> <groupId> IO. Jsonwebtoken </groupId> <artifactId> JJWT </artifactId> <version>0.9.0</version> </dependency>Copy the code
  1. Generate the token, use the Builder () method of the utility 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("White")
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, "liang"// Add other content that is not private. Claim ("companyId"."123456")
                .claim("companyName"."Tencent"); String token = jwtBuilder.compact(); System.out.println(token); }}Copy the code
  1. A user sends a request with a token and parses the token
public class ParseJwt {
    public static void main(String[] args) {
        String token="eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI4OCIsInN1YiI6IuWwj-eZvSIsImlhdCI6MTU5MTE4ODgyNiwiY29tcGFueUlkIjoiMTIzNDU2IiwiY29tcGFueU 5hbWUiOiLohb7orq8ifQ.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()); String companyId = (String) claims. Get (companyId = (String) claims."companyId");
        String companyName = (String) claims.get("companyName"); System.out.println(companyId); System.out.println(companyName); }}Copy the code
  1. Encapsulate generation and parsing as utility 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 String key; Private long TTL; public String createJwtToken(String id, String name, Map<String,Object> Map){// Set invalid time // get current time long now= system.currentTimemillis (); // Current time + valid time = expiration time long exp=now+ TTL; JwtBuilder JwtBuilder = jwts.builder ().setid (id).setSubject(name).setissuedat (new Date()) .signWith(SignatureAlgorithm.HS256, key); Clamis jwtBuilder.setClaims(map); // setExpiration 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();
        returnclaims; }}Copy the code