public class TokenUtils {
//设置过期时间30分钟
private static final long EXPIRE_DATE = 30 * 60 * 1000;
//token秘钥
private static final String TOKEN_SECRET = "UG666UG666UG666";
public static String getToken(User user) {
String token = "";
try {
//过期时间
Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
//秘钥及加密算法
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
//设置头部信息
Map<String, Object> header = new HashMap<>();
header.put("typ", "JWT");
header.put("alg", "HS256");
//携带username,password信息,生成签名
token = JWT.create()
.withHeader(header)
.withClaim("username", user.getName())
.withClaim("password", user.getPwd())
.withExpiresAt(date)
.sign(algorithm);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return token;
}
public static boolean verify(String token) {
/**
* @desc 验证token,通过返回true
* @params [token]需要校验的串
**/
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static String getUserName(String token) {
/**
* @desc 验证token,通过返回true
* @params [token]需要校验的串
**/
try {
Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return jwt.getClaim("username").asString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
User user = new User();
String username ="ug666";
String password = "123";
user.setName(username);
user.setPwd(password);
String token = getToken(user);
System.out.println(token);
boolean b = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTY3MjE0ODk2OCwidXNlcm5hbWUiOiJ1ZzY2NiJ9.MsMBmiHjBOn9r2QmpoQBROEWGTXaWuMVBBGuy8xunpg");
System.out.println(b);
System.out.println(getUserName(token));
System.out.println(verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6IjEyMyIsImV4cCI6MTY3MjE0ODk2OCwidXNlcm5hbWUiOiJ1ZzY2NiJ9.MsMBmiHjBOn9r2QmpoQBROEWGTXaWuMVBBGuy8xunpg"));
}
}
需要添加jwt的maven依赖
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.10.3</version>
</dependency>
配置拦截器InterceptorConfig
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(JWTInterceptor())
.addPathPatterns("/**") //拦截所以请求,通过判断token是否合法,来决定是否需要登录
.excludePathPatterns("/user/login", "/user/logout", "/**/export", "/**/import", "/file/**");
}
@Bean
public JWTInterceptor JWTInterceptor(){
return new JWTInterceptor();
}
}
编写JWTInterceptor拦截器
public class JWTInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token = request.getHeader("token");
// 如果不是映射到方法直接通过
if(!(handler instanceof HandlerMethod)){
return true;
}
// 执行认证
if (token != null){
throw new ServiceException("NOTLOGIN");
}
// 获取token中的user id
String userId;
try{
userId = TokenUtils.getUserName(token);
}catch (JWTDecodeException j){
throw new ServiceException("token验证失败");
}
//根据token中的userid查数据库
User user = userService.getById(userId);
if(user == null){
throw new ServiceException("用户不存在,请重新登录");
}
//用户密码加签验证token
try{
TokenUtils.verify(token);
}catch (JWTVerificationException j){
throw new ServiceException("token验证失败,请重新登录");
}
return true;
}
}
评论