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

ink.huaxun.gateway.util.JwtUtil Maven / Gradle / Ivy

There is a newer version: 4.2.0
Show newest version
package ink.huaxun.gateway.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Payload;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Calendar;
import java.util.Date;

/**
 * 令牌操作工具类
 * @author zhaogang
 * @date 2020-05-25 17:07
 */
public class JwtUtil {

    /**
     * Token秘钥
     */
    private static final String SECRET = "%e7%8e%8b%e6%80%9d%e6%b6%b5";

    /**
     * Token过期时间
     */
    private static final int CALENDAR_FIELD = Calendar.MINUTE;

    private static final int CALENDAR_INTERVAL = 30;

    /**
     * 刷新Token
     * @author zhaogang
     * @date 2020-05-25 17:08
     */
    public static String refreshToken(Payload payload) {
        Calendar now = Calendar.getInstance();
        // 签发时间
        Date issueTime = now.getTime();
        now.add(CALENDAR_FIELD, CALENDAR_INTERVAL);
        // 过期时间
        Date expireTime = now.getTime();

        // 生成Token
        return JWT.create()
                .withIssuer(payload.getIssuer())
                .withAudience(payload.getAudience() != null ? payload.getAudience().toArray(ArrayUtils.EMPTY_STRING_ARRAY) : null)
                .withSubject(payload.getSubject())
                .withIssuedAt(issueTime)
                .withExpiresAt(expireTime)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 解密Token获取Decoded
     * @author zhaogang
     * @date 2020-05-25 17:08
     */
    public static DecodedJWT getDecoded(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        try {
            return verifier.verify(token);
        } catch (JWTVerificationException | IllegalArgumentException error) {
            return null;
        }
    }

    /**
     * 校验payload
     * @author zhaogang
     * @date 2020-05-26 17:43
     */
    public static boolean verifyPayload(Payload payload) {
        // 不予验证Token
        return payload != null;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy