java生成jwt

依赖


		
			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;
    }

}

 

你可能感兴趣的:(java)