springboot中提供了一个非常便捷的拦截器:HandlerInterceptorAdapter
第一步:我们只需要新建一个拦截类实现HandlerInterceptorAdapter,实现preHandle方法,preHandle方法里面就需要写一些拦截的机制
public class ServiceManageRestInterceptorextends HandlerInterceptorAdapter{
private Loggerlogger = LoggerFactory.getLogger(ServiceManageRestInterceptor.class);
@Autowired
private JWTUtiljwtUtil;
@Value("${token-header}")
private StringtokenHeader;
private ListallowedClient;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception {
HandlerMethod handlerMethod = (HandlerMethod) handler;
// // 配置该注解,说明不进行服务拦截
// IgnoreClientToken annotation = handlerMethod.getBeanType().getAnnotation(IgnoreClientToken.class);
// if (annotation == null) {
// annotation = handlerMethod.getMethodAnnotation(IgnoreClientToken.class);
// }
// if(annotation!=null) {
// return super.preHandle(request, response, handler);
// }
// String token = request.getHeader(serviceAuthConfig.getTokenHeader());
// IJWTInfo infoFromToken = serviceAuthUtil.getInfoFromToken(token);
// String uniqueName = infoFromToken.getUniqueName();
// for(String client:serviceAuthUtil.getAllowedClient()){
// if(client.equals(uniqueName)){
// return super.preHandle(request, response, handler);
// }
// }
throw new ClientForbiddenException("Client is Forbidden!");
}
}
注意上面这个子类不需要进行@Component /@Configuration的配置
第二步:我们需要写一个配置类来吧这个拦截器配置到spring中,这个配置类需要实现WebMvcConfigurer
@Configuration("schoolManageWebConfig")
@Primary
public class WebConfigurationimplements WebMvcConfigurer {
@Bean
GlobalExceptionHandler getGlobalExceptionHandler() {
return new GlobalExceptionHandler();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getServiceManageRestInterceptor()).
addPathPatterns(getIncludePathPatterns());
}
@Bean
ServiceManageRestInterceptor getServiceManageRestInterceptor() {
return new ServiceManageRestInterceptor();
}
/**
* 需要用户和服务认证判断的路径
* @return
*/
private ArrayList getIncludePathPatterns() {
ArrayList list =new ArrayList<>();
String[] urls = {
"/**"
};
Collections.addAll(list, urls);
return list;
}
}
这个配置类中registry.addInterceptor(getServiceManageRestInterceptor())这一步就把我们刚才新建的拦截器加入到了spring管理中。getIncludePathPatterns方法我们自定义了一些拦截的方法名的规则。
这样一个module的拦截器就实现了,这个拦截器里面主要就是检查用户token的状态。
网友评论