JAva生成jwt

2178 ワード

に頼る

		
			com.auth0
			java-jwt
			3.4.1
		

JAva生成jwt
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

public class JWTUtil {

    private static final String EXP = "exp";

    private static final String PAYLOAD = "payload";

    private static Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    /**
     *     token
     * @param object     
     * @param maxAge      
     * @param secret       
     * @param 
     * @return
     */
    public static  String createToken(T object, long maxAge, String secret) {
        try {
            final Algorithm signer = Algorithm.HMAC256(secret);//    
            String token = JWT.create()
                    .withIssuer("   ")
                    .withSubject("  ")//  ,  
                    .withClaim("userid", 1234)
                    .withExpiresAt(new Date(System.currentTimeMillis()+maxAge))
                    .sign(signer);
            return token;
        } catch(Exception e) {
            e.printStackTrace();
            logger.error("  token  :",e);
            return null;
        }
    }

    /**
     *     token
     * @param token     token   
     * @param secret      
     * @return
     */
    public static Boolean verifyToken(String token ,String secret) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(secret);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            System.out.println("    ");
        }
        return false;
    }

}