JwtProvider.java 1.67 KB
package com.glsx.usedcar.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.summerframework.web.auth.AbstractJwtProvider;

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


/**
 * JWT认证服务
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class JwtProvider extends AbstractJwtProvider {
    /**
     * 生成token
     *
     * @return token
     */
    public String generateUser(String phone, Date expireTime) {
        try {
            return JWT.create()
                    .withIssuer(jwtProperties.getIssuer())
                    .withIssuedAt(new Date())
                    .withExpiresAt(expireTime)
                    .withJWTId(phone)
                    .withSubject(phone)
                    .sign(algorithm);
        } catch (IllegalArgumentException | TokenExpiredException e) {
            return null;
        }
    }

    public LocalDateTime getExpireTime() {
        LocalDateTime now = LocalDateTime.now();
        return now.plusSeconds(jwtProperties.getExpiration());
    }


    /**
     * 解析token
     *
     * @param token token
     * @return phone
     */
    public String verify(String token) {
        if (token == null) {
            return null;
        }
        try {
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getSubject();
        } catch (Exception e) {
            return null;
        }
    }


}