在弹簧引导库的上下文中添加新弹簧安全链过滤器的预期方式



我正在开发一个库,它引入了一个新的身份验证过滤器,应该在spring安全链中使用

我知道我可以通过以下方式添加过滤器:

@EnableResourceServer
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true)
class AmazingSecurityConfiguration extends WebSecurityConfigurerAdapter {

// filter bean
@Autowired 
private MyFilter myFilter;
@Override
public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
// ... bunch of requirements per path
// ... or ignore path "/bla"
// etc.
.anyRequest().authenticated();

http.addFilterBefore(myFilter.getFilter(), 
AbstractPreAuthenticatedProcessingFilter.class);
}
}

然而,这与用户定义的配置不兼容。实际上,我想在我的库AutoConfig类中配置这个bean,它是由spring工厂触发的。

在网上,我看到了一些例子,它们自己扩展WebSecurityConfigurerAdapter类,并让用户扩展这个新配置。但我不知道这是否会阻止用户做其他事情,而且它还依赖于用户首先调用super.configure(http)来加载过滤器。

这里正确的路是什么?

我能够通过篡改自动配置中bean的调用顺序来配置我自己的http配置

@Configuration
@ConditionalOnClass(WebSecurityConfigurerAdapter.class)
// Two annotations below ensure that this is not the only WebSecurityConfigurerAdapter,
// as it might otherwise disable security for the rest of the application
// The Order ensures that Spring default which uses ConditionalOnMissingBean is still configured before this class
@AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE)
@ConditionalOnBean(WebSecurityConfigurerAdapter.class)
class LibraryFooSecurityConfig {
@RequiredArgsConstructor
@Configuration
@Order(Ordered.HIGHEST_PRECEDENCE)
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// autowired in from elsewhere in the autoconfig
private final MyFilter filter;
@Override
public void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(filter,
AbstractPreAuthenticatedProcessingFilter.class);
}
}
}

这允许用户定义的安全配置扩展WebSecurityConfigurerAdapter并应用它们自己的规则,同时仍然允许我们的库在实际的春季启动应用程序的之后添加它自己的项

最新更新