AccountJwtProvider.java 1.9 KB
package com.glsx.usedcar.web;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.glsx.usedcar.module.account.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.summerframework.web.auth.AbstractJwtProvider;

import java.util.Date;


/**
 * JWT认证服务
 */
@Slf4j
@Component
public class AccountJwtProvider extends AbstractJwtProvider {

    protected static final String MOBILE = "mobile";
    protected static final String AVATAR = "avatar";

    /**
     * 生成token
     *
     * @param account user
     * @return token
     */
    public String generateAccount(Account account) {
        try {
            return JWT.create()
                    .withIssuer(jwtProperties.getIssuer())
                    .withIssuedAt(new Date())
                    .withExpiresAt(new Date(System.currentTimeMillis() + jwtProperties.getExpiration() * 1000))
                    .withJWTId(String.valueOf(account.getAccountId()))
                    .withSubject(account.getAccountName())
                    .withClaim(MOBILE, account.getMobile())
                    .sign(algorithm);
        } catch (IllegalArgumentException | TokenExpiredException e) {
            return null;
        }
    }

    /**
     * 解析token
     *
     * @param token token
     * @return User
     */
    public Account verifyAccount(String token) {
        if (token == null) {
            return null;
        }
        Account account = null;
        try {
            DecodedJWT jwt = verifier.verify(token);
            // 获取用户的权限
            String mobile = jwt.getClaim(MOBILE).asString();
            account = new Account(Integer.parseInt(jwt.getId()), jwt.getSubject(), mobile);
        } catch (Exception e) {
            log.error("token解析失败");
        }
        return account;
    }
}