java写一个用户登陆的jwt工具类

好的,这是一个使用Java编写的JWT工具类供用户登录:

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JWTUtil {

    // 私钥
    private static final String SECRET = "my_secret";

    // 签发者
    private static final String ISSUER = "my_issuer";

    // 过期时间,单位秒
    private static final long EXPIRATION_TIME = 3600;

    // 生成Token
    public static String createToken(String username) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            Date now = new Date();
            long expirationTime = now.getTime() + EXPIRATION_TIME * 1000;
            Date expirationDate = new Date(expirationTime);
            return JWT.create()
                    .withIssuer(ISSUER)
                    .withClaim("username", username)
                    .withExpiresAt(expirationDate)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException | JWTCreationException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 验证Token
    public static boolean verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build()
                    .verify(token);
            return true;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return false;
    }

    // 获取Token中的信息
    public static String getUsername(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            DecodedJWT jwt = JWT.require(algorithm)
                    .withIssuer(ISSUER)
                    .build()
                    .verify(token);
            return jwt.getClaim("username").asString();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

在这个工具类中,我们使用了Auth0的java-jwt库来生成和验证JWT。

使用方法如下:

  • 生成Token:
String token= JWTUtil.createToken("John Doe");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值