1、创建拦截器
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 统一完成根据token查询用User的功能
*/
@Component
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
NoAuthorization noAnnotation = handlerMethod.getMethod().getAnnotation(NoAuthorization.class);
if (noAnnotation != null) {
// 如果该方法被标记为无需验证token,直接返回即可
return true;
}
}
String token = request.getHeader("Authorization");
if (StringUtils.isNotEmpty(token)) {
User user = this.userService.queryUserByToken(token);
if (null != user) {
UserThreadLocal.set(user); //将当前对象,存储到当前的线程中
return true;
}
}
//请求头中如不存在Authorization直接返回false
response.setStatus(401); //无权限访问
return false;
}
}
2、注册拦截器(可注册多个,注意拦截顺序)
import org.springframework.beans.factory.annotation.Autowired;
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 {
@Autowired
private RedisCacheInterceptor redisCacheInterceptor;
@Autowired
private TokenInterceptor tokenInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注意拦截器的顺序
registry.addInterceptor(this.tokenInterceptor).addPathPatterns("/**");
registry.addInterceptor(this.redisCacheInterceptor).addPathPatterns("/**");
}
}
3、从本地线程中获取拦截器存放的用户数据
public class UserThreadLocal {
private static final ThreadLocal<User> LOCAL = new ThreadLocal<User>();
private UserThreadLocal() {
}
public static void set(User user) {
LOCAL.set(user);
}
public static User get() {
return LOCAL.get();
}
}