天天看點

JWT 工具

可以根據解析的結果得出token還有多久過期

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;

public class JwtUtils {

    static String secret = "secret";

    public static String generateToken()  {
        Instant instant = LocalDateTime.now().plusHours(2).atZone(ZoneId.systemDefault()).toInstant();
        return Jwts.builder()
                .claim("id", "0")
                .claim("name","小蘇")
                .setExpiration(Date.from(instant))
                .signWith(SignatureAlgorithm.HS256, secret)
                .compact();
    }

    private static Claims parserToken(String token)  {
        Claims claims = Jwts.parser().setSigningKey("")
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }

    public static void main(String[] args) {
//        String s = generateToken();
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJpZCI6IjAiLCJuYW1lIjoi5bCP6IuPIiwiZXhwIjoxNTkyMTI2NjcyfQ.9N4wQ-uuXNfBWJF1YKbeJIrF3x15MGXsqfwyMApIk9Q";
        Claims claims = parserToken(token);

        System.out.println(claims);
    }
}      
import java.util.Date;
import java.util.concurrent.ExecutionException;

public class Client {


    public static void main(String[] args) throws ExecutionException {
        // 這裡要指定為long類型,否則int會發生溢出,導緻計算不準确
        Date date = new Date(1592126672 * 1000L);
        System.out.println(date);

    }



}