最近系统需要改进授权方式,采用拦截器来拦截请求,
一些不需要拦截的,通过addInterceptor.excludePathPatterns排除掉,排除路径通过配置项注入ignorePath
需要拦截的正常拦截
下面代码中写了两个拦截器,作用如下
一个接口需要在两个系统中使用,一个系统A会带上token校验,另一个系统B没有token校验,所以采用双拦截器分别拦截
mark一下,这里加入两个拦截器
/**
* @author ikong
* @create 2018-06-01 15:22
*/
@ConditionalOnBean(EmployeeValidateInterceptor.class)
@Configuration
public class WebMvcAuthorizationConfig extends WebMvcConfigurerAdapter {
@Value("${ignore-path}")
private String ignorePath = "";
@Override
public void addInterceptors(InterceptorRegistry registry) {
String pathPattern = "/**";
String pathError = "/error";
InterceptorRegistration addInterceptor = registry.addInterceptor(createTokenInterceptorConfig());
addInterceptor.addPathPatterns("/**");
addInterceptor.excludePathPatterns(new String[]{"/error"});
if (!StringUtils.isEmpty(ignorePath)) {
String[] paths = ignorePath.split(";");
for (int i = 0; i < paths.length; i++) {
addInterceptor.excludePathPatterns(new String[]{paths[i]});
}
}
System.out.println("初始化注入过滤路径:" + JSONObject.toJSONString(ignorePath));
InterceptorRegistration employeeInterceptor =registry.addInterceptor(createEmployeeInterceptorConfig());
employeeInterceptor.addPathPatterns(pathPattern);
employeeInterceptor.excludePathPatterns(pathError);
super.addInterceptors(registry);
}
@Bean
public TokenValidateInterceptor createTokenInterceptorConfig() {
return new TokenValidateInterceptor();
}
@Bean
public EmployeeValidateInterceptor createEmployeeInterceptorConfig() {
return new EmployeeValidateInterceptor();
}
}