自定義AuthcInterceptor攔截器類
@Component
@Order(value = 1)
public class AuthcInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//Authenticate 認證
//Authorization 鑒權
if (!(handler instanceof HandlerMethod)) return true;
//存在NoNeedLogin注解 就不做登錄認證了 NoNeedLogin自定義的注解 首先登錄接口就需要添加上該注解
if (((HandlerMethod) handler).getMethodAnnotation(NoNeedLogin.class) != null) return true;
String token = request.getHeader("authenticate");
//這里根據請求頭的信息判斷用戶是否登錄狀態 不是登錄狀態的話 返回401狀態 並拋出異常 NoLoginException 是自定義狀態類
//需要配置全局攔截類檢測到該異常信息就返回必要信息給客戶端,告知客戶端未登錄需要登錄
response.setStatus(401);
throw new NoLoginException();
//這里直接返回true就可以,因為沒有登錄狀態我們也需要返回一些信息
return true;
}
}
自定義配置類 實現 WebMvcConfigurer 類
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Autowired
private AuthcInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
List<String> excludePathPatterns = new ArrayList<>();
excludePathPatterns.add("/error");
//排除攔截swagger-api接口
excludePathPatterns.add("/swagger-resources/**");
//登錄的接口在這里排除 或者 攔截器注解處理
registry.addInterceptor(loginInterceptor).addPathPatterns("/**")
.excludePathPatterns(excludePathPatterns);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//處理靜態文件攔截問題
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/");
registry.addResourceHandler("/wabjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}