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

org.iartisan.runtime.web.utils.JwtUtil Maven / Gradle / Ivy

The newest version!
package org.iartisan.runtime.web.utils;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.iartisan.runtime.env.EnvContextConfig;

import java.util.Date;
import java.util.Map;

/**
 * jwt util
 *
 * @author King  2019/2/25
 */
public class JwtUtil {

    private final static String SECRET = "XX#$%()(#*!()!KL<>?N<:{LWPW";

    private final static String ISSUER = "system";


    private static Algorithm getHS256() {
        return Algorithm.HMAC256(EnvContextConfig.get("jwt.secert", SECRET));
    }

    private static String getIssuer() {
        return EnvContextConfig.get("jwt.issuer", ISSUER);
    }

    /**
     * jwt encode
     *
     * @param claims 要求
     * @param exp    过期时间
     * @return
     */
    public static String encode(Map claims, long exp) {
        Date date = new Date(System.currentTimeMillis() + exp);
        Algorithm algorithm = getHS256();
        JWTCreator.Builder builder = JWT.create();
        claims.forEach((v, k) -> {
            builder.withClaim(v, k);
        });
        return builder.withIssuer(getIssuer()).withExpiresAt(date).sign(algorithm);
    }

    /**
     * jwt decode
     *
     * @param token
     * @return
     */
    public static Map decode(String token) {
        Algorithm algorithm = getHS256();
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(getIssuer()).build();
        DecodedJWT result = verifier.verify(token);
        Map claims = result.getClaims();
        return claims;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy