JwtUtil.java 2.53 KB
package com.example.erp.common.util;

import com.example.erp.common.constants.AuthErrorCode;
import com.example.erp.common.exception.BizException;
import com.example.erp.config.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@RequiredArgsConstructor
public class JwtUtil {

    private final JwtProperties properties;

    private SecretKey key() {
        return Keys.hmacShaKeyFor(properties.getSecret().getBytes(StandardCharsets.UTF_8));
    }

    public String generateAccessToken(String userId, String username, String userType, String brandId) {
        long now = System.currentTimeMillis();
        return Jwts.builder()
                .subject(userId)
                .claim("username", username)
                .claim("userType", userType)
                .claim("brandId", brandId)
                .issuedAt(new Date(now))
                .expiration(new Date(now + properties.getAccessTokenExpiry() * 1000))
                .signWith(key(), Jwts.SIG.HS256)
                .compact();
    }

    public String generateRefreshToken(String userId, String brandId) {
        long now = System.currentTimeMillis();
        return Jwts.builder()
                .subject(userId)
                .claim("brandId", brandId)
                .claim("type", "refresh")
                .issuedAt(new Date(now))
                .expiration(new Date(now + properties.getRefreshTokenExpiry() * 1000))
                .signWith(key(), Jwts.SIG.HS256)
                .compact();
    }

    public Claims parseAccessToken(String token) {
        return doParse(token);
    }

    public Claims parseRefreshToken(String token) {
        Claims claims = doParse(token);
        if (!"refresh".equals(claims.get("type", String.class))) {
            throw new BizException(AuthErrorCode.REFRESH_TOKEN_INVALID, "Refresh Token 已失效,请重新登录");
        }
        return claims;
    }

    private Claims doParse(String token) {
        try {
            return Jwts.parser()
                    .verifyWith(key())
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
        } catch (JwtException e) {
            throw new BizException(AuthErrorCode.REFRESH_TOKEN_INVALID, "Token 已失效,请重新登录");
        }
    }
}