Suppose I have two SecurityFilterChain-Beans configured.
One provides some general security configuration, for example it could set a CSP header. This bean will be part of a library, since I want to apply it across several applications.
@Bean
@Order
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) {
http
// ...
.headers(headers -> headers
.contentSecurityPolicy(policy -> policy
.policyDirectives("script-src 'self' https://trustedscripts.example.com")
)
);
return http.build();
}
The second bean is only applied for one endpoint in one application, which requires specific authorization (very much simplified example):
@Bean
@Order(0)
SecurityFilterChain specialSecurityFilterChain(HttpSecurity http) {
http
.securityMatcher(request -> request.getRequestURI().startsWith("/critical-endpoint")
.authorizeHttpRequests(authorize -> authorize.hasRole("ADMIN"))
return http.build();
}
When processing a request, one SecurityFilterChain gets selected according to their order and the securityMatchers.
However, I’d like to return the same CSP-Header when the specialSecurityFilterChain
was applied, without having to repeat the code from the defaultSecurityFilterChain
. Is there a way to achieve this global kind of configuration for SecurityFilterChains?
I tried replacing the HttpSecurity-Bean and configuring it with a @PostConstruct
-annotated method, but this led to conflicts because of duplicate beans and circular dependencies on application startup respectively.