Spring Boot整合JWT简单实现Token的验证
导入依赖
<!--JWT-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.4.1</version>
</dependency>
源码
public static DecodedJWT decode(String token) throws JWTDecodeException {
return new JWTDecoder(token);
}
public static Verification require(Algorithm algorithm) {
return JWTVerifier.init(algorithm);
}
public static Builder create() {
return JWTCreator.init();
}
简单实现
public static String generateToken(String mobile) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
Date date = new Date(System.currentTimeMillis() + EXPIRED_TIME);
return JWT
.create()
.withClaim("mobile", mobile)
.withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
log.error("generateToken error mobile:{}", mobile);
return null;
}
}
public static Boolean verifyToken(String token, String mobile) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier jwtVerifier = JWT
.require(algorithm)
.withClaim("mobile", mobile)
.build();
jwtVerifier.verify(token);
return true;
} catch (Exception e) {
log.error("verifyToken error mobile:{}", mobile);
return false;
}
}
public static String getMobileByToken(String token) {
try {
DecodedJWT decodedJWT = JWT.decode(token);
return decodedJWT.getClaim("mobile").asString();
} catch (Exception e) {
log.error("getMobileByToken error");
return null;
}
}
测试
public static void main(String[] args) {
String mobile = "18888888888";
String token = JWTUtil.generateToken(mobile);
System.out.println(token);
System.out.println(JWTUtil.verifyToken(token, mobile));
System.out.println(JWTUtil.getMobileByToken(token));
}
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJtb2JpbGUiOiIxODg4ODg4ODg4OCIsImV4cCI6MTYzNjM2NTExOH0.IJCA5SUvOPLrr-kmn3PeEWJK32O3mvrkyav74Ef4ZPM
true
18888888888