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

com.github.dennisit.vplus.data.utils.JWTUtils Maven / Gradle / Ivy

There is a newer version: 2.0.8
Show newest version
package com.github.dennisit.vplus.data.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import com.google.common.collect.ImmutableMap;
import io.jsonwebtoken.*;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Optional;

public final class JWTUtils {

    private JWTUtils() {

    }

    // 默认的唯一标识编号
    public static final String DEFAULT_UID = "uid";

    // 过期时间3天
    public static final int EXPIRE_TIME = 60 * 24 * 30;


    @Deprecated
    public static String jwtUidSign(String uValue, String secret) throws Exception {
        return jwtToken(ImmutableMap.of(DEFAULT_UID, uValue), secret);
    }


    @Deprecated
    public static String jwtUidSign(String uValue, String secret, int expireMinutes) throws Exception {
        return jwtToken(ImmutableMap.of(DEFAULT_UID, uValue), secret, expireMinutes);
    }


    @Deprecated
    public static String jwtUidGet(String token) {
        return jwtKey(DEFAULT_UID, token);
    }


    @Deprecated
    public static boolean jwtUidVerify(String token, String uidValue, String secret) {
        return jwtVerify(token, ImmutableMap.of(DEFAULT_UID, uidValue), secret);
    }

    @Deprecated
    public static boolean jwtVerify(String token, ImmutableMap claim, String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            Verification verification = JWT.require(algorithm);
            Optional.ofNullable(claim).orElse(ImmutableMap.of()).forEach((k, v) -> {
                verification.withClaim(k, v);
            });
            DecodedJWT jwt = verification.build().verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }


    @Deprecated
    public static String jwtKey(String keyName, String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim(keyName).asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名
     *
     * @param claims    可以反解析的键值对信息
     * @param secretKey 安全码/可以是用户密码也可以是内部二次Token
     * @return 签名
     * @throws Exception 异常
     */
    public static String jwtToken(ImmutableMap claims, String secretKey) throws Exception {
        return jwtToken(claims, secretKey, EXPIRE_TIME);
    }

    /**
     * 生成签名
     *
     * @param claim         可以反解析的键值对信息
     * @param secretKey     安全码/可以是用户密码也可以是内部二次Token
     * @param expireMinutes 授权码有效期,单位毫秒
     * @return 签名
     * @throws Exception 异常
     */
    public static String jwtToken(ImmutableMap claim, String secretKey, int expireMinutes) throws Exception {
        JWTCreator.Builder builder = JWT.create().withExpiresAt(DateTime.now().plusMinutes(expireMinutes).toDate());
        Optional.ofNullable(claim).orElse(ImmutableMap.of()).forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        return builder.sign(Algorithm.HMAC256(secretKey));
    }

    //-----------------

    /**
     * 私钥加密token
     *
     * @param claims        载荷中的数据
     * @param privateKey    私钥
     * @param expireMinutes 过期时间,单位秒
     * @return 签名
     * @throws Exception 异常
     */
    public static String jwtToken(ImmutableMap claims, PrivateKey privateKey, int expireMinutes) throws Exception {
        JwtBuilder builder = Jwts.builder();
        Optional.ofNullable(claims).orElse(ImmutableMap.of()).forEach((k, v) -> {
            builder.claim(k, v);
        });
        return builder.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }


    /**
     * 私钥加密token
     *
     * @param claims        载荷中的数据
     * @param privateKey    私钥字节数组
     * @param expireMinutes 过期时间,单位秒
     * @return 签名
     * @throws Exception 异常
     */
    public static String jwtToken(ImmutableMap claims, byte[] privateKey, int expireMinutes) throws Exception {
        JwtBuilder builder = Jwts.builder();
        Optional.ofNullable(claims).orElse(ImmutableMap.of()).forEach((k, v) -> {
            builder.claim(k, v);
        });
        return builder.setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(SignatureAlgorithm.RS256, RSAUtils.getPrivateKey(privateKey))
                .compact();
    }

    /**
     * 公钥解析token
     *
     * @param token     用户请求中的token
     * @param publicKey 公钥
     * @return 签名
     */
    public static Jws jwtParser(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    /**
     * 公钥解析token
     *
     * @param token     用户请求中的token
     * @param publicKey 公钥字节数组
     * @return 签名
     * @throws Exception 异常
     */
    public static Jws jwtParser(String token, byte[] publicKey) throws Exception {
        return Jwts.parser().setSigningKey(RSAUtils.getPublicKey(publicKey))
                .parseClaimsJws(token);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy