package com.ruoyi.web.utils;

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

import java.util.Date;

public class JWTExample {
    private static final String SECRET_KEY = "C97E76AF40CSH12N128SN23B2DB9D476";
    private static final long EXPIRATION_TIME = 86400000; // 24小时

    public static void main(String[] args) {
        // 创建JWT
        String token = createJWT("user123",EXPIRATION_TIME);

        // 验证和解析JWT
        if (validateJWT(token)) {
            String username = parseJWT(token);
            System.out.println("解析到的用户名：" + username);
        } else {
            System.out.println("JWT验证失败");
        }
    }

    public static String createJWT(String str,Long dateTime) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + dateTime);

        String token = Jwts.builder()
                .setSubject(str)
                .setIssuedAt(now)
                .setExpiration(expiration)
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();

        return token;
    }

    public static boolean validateJWT(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static String parseJWT(String token) {
        Jws<Claims> claims = Jwts.parser().setSigningKey(SECRET_KEY).parseClaimsJws(token);
        return claims.getBody().getSubject();
    }
}
