Java中 Jwt

java

jar包

封装工具类

public class jwtTool {


    public static final String secretKey = "askjdksadjkasdakjshdjkasdkAakjshdjasdjs";


    public String getJWTWithHMAC256(String subject, String secretKey){
        //指定JWT所使⽤用的签名算法
        Algorithm algorithm = Algorithm.HMAC256(secretKey);
        String token = JWT.create()//创建token
                .withIssuer("com.kkb")//指定签发⼈人
                .withSubject(subject)//指定主体数据
                .withExpiresAt(new Date(new Date().getTime()+(1000*20)))
                .sign(algorithm);//最终⽣生成 token
        return token;
    }


    public boolean verifyTokenWithHMAC256(String token,String secretKey){
        try{
            Algorithm algorithm = Algorithm.HMAC256(secretKey);
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("com.kkb")
                    .build();
            verifier.verify(token);
            return true;
        }catch (JWTVerificationException e){
            e.printStackTrace();
            return false;
        }
    }


}
DecodedJWT decode = JWT.decode(token);
System.out.println(decode.getSignature());
System.out.println(decode.getSubject());
System.out.println(decode.getExpiresAt());
原文地址:https://www.cnblogs.com/tangshuo/p/12744277.html