JAVA之JWT工具类

本文介绍了一个使用Auth0 JWT库创建和验证JWT令牌的实用工具类。该工具类使用HMAC256算法生成带有过期时间和发行人声明的令牌,并能从令牌中解析用户的唯一标识符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.sxapp.commons.exception.SXException;
import com.sxapp.commons.exception.SXExceptionEnum;
import org.joda.time.DateTime;

public class JwtUtil {
    private final static String SECRET = "324iu23094u598ndsofhsiufhaf_+0wq-42q421jiosadiusadiasd";

    public static String createToken(long uid) {
        Algorithm algorithm = Algorithm.HMAC256(SECRET);
        String token;
        try {
            token = JWT.create()
                    .withIssuer("withissuer")
                    .withExpiresAt(DateTime.now().plusHours(1).toDate())
                    .withClaim("uid", uid)
                    .sign(algorithm);
            return token;
        } catch (JWTCreationException e) {
            throw new SXException(500, e.getMessage());
        }

    }

    public static long verifyToken(String token) {
        DecodedJWT verify;
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTVerifier jwtVerifier = JWT.require(algorithm)
                    .withIssuer("withissuer")
                    .build();
            verify = jwtVerifier.verify(token);
            Claim uid = verify.getClaim("uid");
            return uid.asLong();
        } catch (JWTVerificationException e) {
            throw new SXException(SXExceptionEnum.JWT_PARSE_ERROR);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值