引入依赖

<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.17.0</version>
</dependency>

代码

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
* @Date 2021年6月29日
* @Desc JWT工具类
**/
@Slf4j
public class JwtUtil {

// Token过期时间30分钟(用户登录过期时间是此时间的两倍,以token在reids缓存时间为准)
public static final long EXPIRE_TIME = 30 * 60 * 1000;

/**
* 校验token是否正确
*
* @param token 密钥
* @param secret 用户的密码
* @return 是否正确
*/
public static boolean verify(String token, String username, String secret) {
try {
// 根据密码生成JWT效验器
Algorithm algorithm = Algorithm.HMAC256(secret);
JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
// 效验TOKEN
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception exception) {
return false;
}
}

/**
* 获得token中的信息无需secret解密也能获得
*
* @return token中包含的用户名
*/
public static String getUsername(String token) {
try {
DecodedJWT jwt = JWT.decode(token);
return jwt.getClaim("username").asString();
} catch (JWTDecodeException e) {
return null;
}
}

/**
* 生成签名,5min后过期
* (生成token)
* @param username 用户名
* @param secret 用户的密码
* @return 加密的token
*/
public static String sign(String username, String secret) {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(secret);
// 附带username信息
return JWT.create().withClaim("username", username).withExpiresAt(date).sign(algorithm);

}

/**
* 根据request中的token获取用户账号
*
* @param request
* @return
* @throws Exception
*/
public static String getUserNameByToken(HttpServletRequest request) throws Exception {
String accessToken = request.getHeader("X-Access-Token");
String username = getUsername(accessToken);
if (StrUtil.isEmpty(username)) {
throw new Exception("未获取到用户");
}
return username;
}


public static void main(String[] args) {
String username = "admin";
String password = "123456";
//第一步 生成token
String token = JwtUtil.sign(username, password);

log.info("token={}", token);
String username1 = JwtUtil.getUsername(token);
log.info("username={}", username1);
}
}