All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.itheima.auth.sdk.service.TokenCheckService Maven / Gradle / Ivy

package com.itheima.auth.sdk.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import com.itheima.auth.sdk.common.AuthSdkException;
import com.itheima.auth.sdk.dto.AuthUserInfoDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;

import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;


/**
 * token校验的服务类
 *
 * @author zzj
 * @version 1.0
 */
public class TokenCheckService {

    /**
     * 公钥文件路径,可以是绝对路径,也可以是相对路径(相对ClassPath),如果提供路径为绝对路径或路径以file:开头
     */
    private String publicKeyFile;

    public TokenCheckService(String publicKeyFile) {
        this.publicKeyFile = publicKeyFile;
    }

    /**
     * 解析校验token,如果失效或伪造token抛出异常,反之返回token中的数据
     * @param token
     * @return
     * @throws AuthSdkException
     */
    public AuthUserInfoDTO parserToken(String token) throws AuthSdkException {
        try {
            PublicKey publicKey = getPublicKey();
            //未配置公钥的情况下本地不做校验
            if (publicKey == null) {
                return null;
            }
            Jws jws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
            return BeanUtil.toBean(jws.getBody(), AuthUserInfoDTO.class);
        } catch (ExpiredJwtException var3) {
            throw new AuthSdkException("token已过期");
        } catch (Exception var6) {
            var6.printStackTrace();
            throw new AuthSdkException("token不合法");
        }
    }

    /**
     * 读取公钥
     *
     * @return
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    private PublicKey getPublicKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
        PublicKey publicKey;
        try {
            X509EncodedKeySpec spec = new X509EncodedKeySpec(ResourceUtil.readBytes(this.publicKeyFile));
            KeyFactory kf = KeyFactory.getInstance("RSA");
            publicKey = kf.generatePublic(spec);
        } catch (Exception e) {
            throw e;
        }
        return publicKey;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy