好的,这是一个使用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");
- 验