JwtUtil
package com.sxwy.mybatisplus.interceptor;
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.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
/**
* jwt工具类
*/
public class JwtUtil {
/**
* 过期时间5分钟
*/
private static final long EXPIRE_TIME = 5 * 60 * 1000;
/**
* jwt 密钥
*/
private static final String SECRET = "jwt_secret";
/**
* 生成签名,五分钟后过期
*
* @param userId
* @return
*/
public static String sign(String userId) {
try {
Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
Algorithm algorithm = Algorithm.HMAC256(SECRET);
return JWT.create()
// 将 userId 保存到 token 里面
.withAudience(userId)
// 五分钟后token过期
.withExpiresAt(date)
// token 的密钥
.sign(algorithm);
} catch (Exception e) {
return null;
}
}
/**
* 根据 token 获取 userId
*
* @param token
* @return
*/
public static String getUserId(String token) {
try {
String userId = JWT.decode(token).getAudience().get(0);
return userId;
} catch (JWTDecodeException e) {
return null;
}
}
/**
* 校验token
*
* @param token
* @return
*/
public static boolean checkSign(String token) {
try {
Algorithm algorithm = Algorithm.HMAC256(SECRET);
JWTVerifier verifier = JWT.require(algorithm)
// .withClaim("username", username)
.build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (JWTVerificationException exception) {
// throw new RuntimeException("token 无效,请重新获取");
throw new JwtExpiredException("token 无效,请重新获取");
}
}
}
JwtInterceptor
package com.sxwy.mybatisplus.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* jwt拦截器
*/
@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// UserContext.setUser(Long.valueOf());
// System.out.println(JwtUtil.getUserId(request.getHeader("token")));
UserContext.setUser(Long.valueOf(JwtUtil.getUserId(request.getHeader("token"))));
return JwtUtil.checkSign(request.getHeader("token"));
}
}
UserContext
package com.sxwy.mybatisplus.interceptor;
public class UserContext {
private static final ThreadLocal<Long> TL = new ThreadLocal<>();
/**
* 保存用户信息
*
* @param userId 用户id
*/
public static void setUser(Long userId) {
TL.set(userId);
}
/**
* 获取用户
*
* @return 用户id
*/
public static Long getUser() {
return TL.get();
}
/**
* 移除用户信息
*/
public static void removeUser() {
TL.remove();
}
}
webConfig
package com.sxwy.mybatisplus.interceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 注册拦截器
*/
@Configuration
public class webConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new JwtInterceptor()).addPathPatterns("/**").excludePathPatterns("/public/Register");
}
}
JwtExpiredException
package com.sxwy.mybatisplus.interceptor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(code = HttpStatus.UNAUTHORIZED)
public class JwtExpiredException extends RuntimeException {
public JwtExpiredException(String message) {
super(message);
}
}
GlobalExceptionHandler
package com.sxwy.mybatisplus.interceptor;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局异常处理
*/
// @RestControllerAdvice
public class GlobalExceptionHandler {
@ResponseBody
@ExceptionHandler(Exception.class)
public Object handleException(Exception e) {
String msg = e.getMessage();
if (msg == null || msg.equals("")) {
msg = "服务器出错";
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 500);
jsonObject.put("message", msg);
return jsonObject;
}
@ResponseBody
@ExceptionHandler(JwtExpiredException.class)
public Object JwtExpiredException(Exception e) {
String msg = e.getMessage();
if (msg == null || msg.equals("")) {
msg = "服务器出错";
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("code", 500);
jsonObject.put("message", msg);
return jsonObject;
}
}