JWT生成token

粘一下之前使用的生成token的方法

/**
 * 加密
 * @author shihao
 *
 */
public final class Encrypt {

    /**
     * 生成加密后的token
     * @param isVip 是不是VIP,true表示是VIP,false表示不是VIP。
     * @param userId 用户id
     * @param Type  类型
     * @return 加密后的token
     */
    public String getToken(final boolean isVip, final Integer userId,
                           final String Type,Integer merId) {
        String token = null;
        try {
            Date expiresAt = new Date(System.currentTimeMillis() + 24L * 60L * 3600L * 1000L);
            token = JWT.create()
                    .withIssuer("auth0")
                    .withClaim("isVip", isVip)
                    .withClaim("merId",merId)
                    .withClaim("userId", userId)
                    .withClaim("Type", Type)
                    .withExpiresAt(expiresAt)
                    // 使用了HMAC256加密算法。
                    // mysecret是用来加密数字签名的密钥。
                    .sign(Algorithm.HMAC256("mysecret"));
        } catch (JWTCreationException exception){
            //Invalid Signing configuration / Couldn't convert Claims.
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return token;
    }
}
/**
 * 解密
 * @author shihao
 *
 */
public final class Decrypt {

    /**
     * 先验证token是否被伪造,然后解码token。
     * @param token 字符串token
     * @return 解密后的DecodedJWT对象,可以读取token中的数据。
     */
    public DecodedJWT deToken(final String token) {
        DecodedJWT jwt = null;
        try {
            // 使用了HMAC256加密算法。
            // mysecret是用来加密数字签名的密钥。
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256("mysecret"))
                    .withIssuer("auth0")
                    .build(); //Reusable verifier instance
            jwt = verifier.verify(token);
        } catch (JWTVerificationException exception){
            //Invalid signature/claims
            exception.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return jwt;
    }
}
posted @ 2021-08-18 17:44  叶璃溪  阅读(321)  评论(0)    收藏  举报
Live2D