1.导入依赖
<!--JWT-->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
2.创建TokenUtils
import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.ethan.exam_ms.entity.User;
import com.ethan.exam_ms.exception.ServiceException;
import java.util.Calendar;
import java.util.Date;
public class TokenUtils {
//密钥
public static final String SECRET = "areyoucrazy?pojie?bukenengde?";
//过期时间:秒
public static final int EXPIRE = 30;
public static String getToken(String id,String username){
Calendar nowTime = Calendar.getInstance();
//过期时间
nowTime.add(Calendar.SECOND, EXPIRE);
Date expireDate = nowTime.getTime();
String token = JWT.create()
//这是在设置第二部分信息,不要设置密码之类的,因为这些信息可以通过浏览器获取
//用户id
.withClaim("id", id)
//用户名
.withClaim("username",username)
//创建token的时间
.withIssuedAt(new Date())//签名时间
//设置token的过期时间
.withExpiresAt(expireDate)//过期时间
//设置第一部分
.sign(Algorithm.HMAC256(SECRET));//签名
return token;
}
/**
* 验证token合法性 成功返回token
*/
public static DecodedJWT verify(String token) throws ServiceException {
if(StrUtil.isBlank(token)){
throw new ServiceException("token不能为空");
}
JWTVerifier build = JWT.require(Algorithm.HMAC256(SECRET)).build();
return build.verify(token);
}
}
3.登录拦截器
(1)没有统一返回类,用map封装

文章展示了如何在Java应用中使用JWT(JSONWebTokens)进行权限管理。通过创建TokenUtils工具类生成和验证JWT,设置过期时间和密钥。同时,文章还介绍了登录拦截器的实现,检查请求头中的token并处理不同类型的验证异常,如无效签名、过期或算法不匹配。最后,提到了在SpringMVC中配置拦截器的步骤。
最低0.47元/天 解锁文章
194





