背景
项目中自定义了拦截器Filter
,项目中使用了spring security
,它也有对应的拦截器,我想让我自定义的Filter
在spring security
的拦截器前执行。
因为我自定义的拦截器,需要提前做一些逻辑处理;然后spring security
的拦截器需要用到这部分的处理结果;所以我必须要想办法让我自定义的拦截器靠前执行。
那就一起来看看spring security
设置的拦截器的默认优先级等级是多少吧。
模拟场景
自定义拦截器如下:
@Slf4j
public class MyOncePerRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
log.info("======== MyOncePerRequestFilter ========");
filterChain.doFilter(request, response);
}
}
@Configuration
public class Config {
@Bean
public FilterRegistrationBean<MyOncePerRequestFilter> i18nFilterRegistrationBean() {
FilterRegistrationBean<MyOncePerRequestFilter> registrationBean = new FilterRegistrationBean();
MyOncePerRequestFilter myOncePerRequestFilter = new MyOncePerRequestFilter();
registrationBean.setFilter(myOncePerRequestFilter);
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(-1);
return registrationBean;
}
}
spring security
的简单配置如下:
@Slf4j
public class MyTokenStore implements TokenStore {
@Override
public OAuth2AccessToken readAccessToken(String tokenValue) {
log.info("======== readAccessToken ========");
return new DefaultOAuth2AccessToken(tokenValue);
}
@Override
public OAuth2Authentication readAuthentication(OAuth2AccessToken token) {
Authentication authentication = new AbstractAuthenticationToken(Sets.newHashSet()) {
{
super.setAuthenticated(true);
}
@Override
public Object getCredentials() {
return null;
}
@Override
public Object getPrincipal() {
return StringUtils.EMPTY;
}
};
OAuth2Request request =
new OAuth2Request(null, null, null, true,
Sets.newHashSet(), Sets.newHashSet(), null, null, null);
return new OAuth2Authentication(request, authentication);
}
@Override public OAuth2Authentication readAuthentication(String token) {
return null;
}
@Override
public void storeAccessToken(OAuth2AccessToken token, OAuth2Authentication authentication) {
}
@Override public void removeAccessToken(OAuth2AccessToken token) {
}
@Override public void storeRefreshToken(OAuth2RefreshToken refreshToken, OAuth2Authentication authentication) {
}
@Override public OAuth2RefreshToken readRefreshToken(String tokenValue) {
return null;
}
@Override public OAuth2Authentication readAuthenticationForRefreshToken(OAuth2RefreshToken token) {
return null;
}
@Override public void removeRefreshToken(OAuth2RefreshToken token) {
}
@Override public void removeAccessTokenUsingRefreshToken(OAuth2RefreshToken refreshToken) {
}
@Override public OAuth2AccessToken getAccessToken(OAuth2Authentication authentication) {
return null;
}
@Override public Collection<OAuth2AccessToken> findTokensByClientIdAndUserName(String clientId, String userName) {
return null;
}
@Override public Collection<OAuth2AccessToken> findTokensByClientId(String clientId) {
return null;
}
}
@Configuration
@EnableResourceServer
@EnableWebSecurity
public class MyResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer resources) {
MyTokenStore tokenStore = new MyTokenStore();
resources.tokenStore(tokenStore);
}
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests().anyRequest().authenticated()
.and().anonymous().key("anonymousUser")
.and().httpBasic();
}
}
启动类如下:
@RestController
public class MyController {
@GetMapping("/hello")
public String hello() {
return "hello,world!";
}
}
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class Starter {
public static void main(String[] args) {
SpringApplication.run(Starter.class, args);
}
}
启动后,访问 http://127.0.0.1:8080/hello?access_token=123
日志打印如下:
102149 [http-nio-8080-exec-1] INFO c.e.l.s.mvc.security.MyTokenStore - ======== readAccessToken ========
102149 [http-nio-8080-exec-1] INFO c.e.l.s.m.s.MyOncePerRequestFilter - ======== MyOncePerRequestFilter ========
从结果可以看出,spring security
的拦截器是比我们自定义的拦截器先执行的,而我们自定义的拦截器的优先级是registrationBean.setOrder(-1)
我猜应该是这个值决定了执行顺序,那就带着这个猜想往下看一下吧。
是不是因为order
的值
在之前的配置中,我们将自定义的拦截器顺序置为-1
我们先在MyOncePerRequestFilter.doFilterInternal
打个断点,看一下执行链的顺序:
从这条链中,我们猜测springSecurityFilterChain
的order
是-100
,我们自定义的拦截器是在它后面的
那我们直接把我们的拦截器设置成-101
,registrationBean.setOrder(-101);
,再来尝试一下:
从断点结果可以看出,我们的设置是有效的,并且起到了作用,而且打印日志也说明了结果,如下:
11956 [http-nio-8080-exec-1] INFO c.e.l.s.m.s.MyOncePerRequestFilter - ======== MyOncePerRequestFilter ========
98419 [http-nio-8080-exec-1] INFO c.e.l.s.mvc.security.MyTokenStore - ======== readAccessToken ========
找出在哪里赋予的order
值
这个过程是极其枯燥的,所以就先给结果了,如下:
spring security
的拦截器链是在下面这部分创建的:
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@EnableConfigurationProperties(SecurityProperties.class)
@ConditionalOnClass({ AbstractSecurityWebApplicationInitializer.class, SessionCreationPolicy.class })
@AutoConfigureAfter(SecurityAutoConfiguration.class)
public class SecurityFilterAutoConfiguration {
private static final String DEFAULT_FILTER_NAME = AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME;
@Bean
@ConditionalOnBean(name = DEFAULT_FILTER_NAME)
public DelegatingFilterProxyRegistrationBean securityFilterChainRegistration(
SecurityProperties securityProperties) {
DelegatingFilterProxyRegistrationBean registration = new DelegatingFilterProxyRegistrationBean(
DEFAULT_FILTER_NAME);
registration.setOrder(securityProperties.getFilter().getOrder()); // 这里
registration.setDispatcherTypes(getDispatcherTypes(securityProperties));
return registration;
}
}
public abstract class AbstractSecurityWebApplicationInitializer implements WebApplicationInitializer {
public static final String DEFAULT_FILTER_NAME = "springSecurityFilterChain";
}
@ConfigurationProperties(prefix = "spring.security")
public class SecurityProperties {
public static final int DEFAULT_FILTER_ORDER = OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100; // 这里
private final Filter filter = new Filter();
public Filter getFilter() {
return this.filter;
}
public static class Filter {
private int order = DEFAULT_FILTER_ORDER; // 这里
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
}
}
public interface OrderedFilter extends Filter, Ordered {
int REQUEST_WRAPPER_FILTER_MAX_ORDER = 0; // 这里
}
从上面的代码可以看出,默认值是-100
,同样也可以使用spring.security.filter.order
来自定义值。
下面是寻找此过程的历程:
继续从这里开始,ApplicationFilterChain.internalDoFilter
如下:
可以看出所有的拦截器都是在filters
中,我们可以看这个值是怎么来的,通过调试,是在ApplicationFilterChain.addFilter
这个地方,如下:
它是被ApplicationFilterFactory.createFilterChain
调用的,如下:
所以filters
是根据filterMaps
来添加的,我们再来看一下filterMaps
是怎么来的,一共涉及到两个地方,如下:
StandardContext.addFilterMap
和StandardContext.addFilterMapBefore
如下:
看一下调用链:
原来是被ServletWebServerApplicationContext.selfInitialize
调用的,如下:
ServletWebServerApplicationContext.getServletContextInitializerBeans
如下:
ServletContextInitializerBeans
构造函数如下:
所有的拦截器都是通过addServletContextInitializerBeans(beanFactory);
和addAdaptableBeans(beanFactory);
来把bean
加进来的
经过一番调试,终于找到spring security
这个拦截器定义顺序的位置,SecurityFilterAutoConfiguration.securityFilterChainRegistration
如下:
可以看到SecurityProperties securityProperties
是注入进来的,找到这个类看一下,securityProperties.filter.order
如下:
@ConfigurationProperties(prefix = "spring.security")
public class SecurityProperties {
public static final int DEFAULT_FILTER_ORDER = OrderedFilter.REQUEST_WRAPPER_FILTER_MAX_ORDER - 100;
private final Filter filter = new Filter();
private final User user = new User();
public static class Filter {
/**
* Security filter chain order.
*/
private int order = DEFAULT_FILTER_ORDER;
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
}
}
public interface OrderedFilter extends Filter, Ordered {
/**
* Filters that wrap the servlet request should be ordered less than or equal to this.
*/
int REQUEST_WRAPPER_FILTER_MAX_ORDER = 0;
}
到此我们也找到了这个默认值,是根据spring.security.filter.order
来决定的,默认值是-100
解决办法
第一种就是修改自己的顺序:
@Configuration
public class Config {
@Bean
public FilterRegistrationBean<MyOncePerRequestFilter> i18nFilterRegistrationBean() {
FilterRegistrationBean<MyOncePerRequestFilter> registrationBean = new FilterRegistrationBean();
MyOncePerRequestFilter myOncePerRequestFilter = new MyOncePerRequestFilter();
registrationBean.setFilter(myOncePerRequestFilter);
registrationBean.addUrlPatterns("/*");
registrationBean.setOrder(-101); // 这里
return registrationBean;
}
}
第二种就是修改spring security
拦截器的顺序:
spring:
security:
filter:
order: 0
大家可以自己跑跑试试看,完结撒花~~~~~~