依赖

        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>4.0.0</version>
        </dependency>

JWTUtil 工具包

public class JWTUtils {
    //Edition是对象
    public static String createJWT(Edition edition){
        //声明签名的算法。 1.参数为密钥,注意密钥只能后端知晓,因为密钥泄露代表可以任意对生成的jwt串进行解密
        Algorithm algorithm = Algorithm.HMAC256("secret");
        //2.声明头部
        Map map = new HashMap<>();
        //声明加密算法
        map.put("alg","HS256");
        //声明类型 jwt 固定值
        map.put("typ","JWT");

        //3.声明载荷 并且创建出jwt串
        String token = JWT.create()
                //设置头部
                .withHeader(map)
                //载荷中的公共信息。签发人。任意填写即可
                .withIssuer("test")
                //载荷中的公共信息 受众,通常指用户
                .withAudience("edition")
                //载荷中的自定义信息。key:value的存储格式,任意存储内容。
                .withClaim("editionSecretKey", edition.getEditionSecretKey())
                .withClaim("catalogueVersions", edition.getCatalogueVersions())
//                .withClaim("id", user.get("id").toString())
                //使用定义好的签名算法
                .sign(algorithm);
        return token;
    }

//判断秘钥是否存在
    public static Boolean verifyToken(String token){
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret"); //use more secure key
            //创建jwt的解密对象
            JWTVerifier verifier = JWT.require(algorithm)
                    //注意 解密的签发人要与加密的签发人保持一致
                    .withIssuer("test")
                    .build(); //Reusable verifier instance
            //对token进行解密
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    //把token秘钥里的catalogueVersions解密
    public static Integer getCatalogueVersions(String token) {
        //声明签名算法,注意:加密的密钥与解密的密钥保持一致,如果没有一致则无法解密
        Algorithm algorithm = Algorithm.HMAC256("secret"); //use more secure key
        //创建jwt的解密对象
        JWTVerifier verifier = JWT.require(algorithm)
                //注意 解密的签发人要与加密的签发人保持一致
                .withIssuer("test")
                .build(); //Reusable verifier instance
        //对token进行解密
        DecodedJWT jwt = verifier.verify(token);
        //我们就可以从jwt中获取到自定义的用户名称
        System.out.println("图书秘钥:"+jwt.getClaim("editionSecretKey").asString());
        System.out.println("catalogueVersions:"+jwt.getClaim("catalogueVersions").asInt());
        return jwt.getClaim("catalogueVersions").asInt();
    }
}

  

posted on 2023-02-26 13:49  鲤斌  阅读(42)  评论(0)    收藏  举报