Expected Behavior
I would like to be able to configure Csrf the same way as CORS so that i can control it by using the @Profile annotations.
For instance:
@Bean
@Profile("!Prod")
public CsrfConfigurationSource csrf() {
return new CsrfConfigurationSource()
.disabled()
.build()
}
would like to be able to define a CsrfConfigurationSource in a @Bean that will be used so that it is possible to configure Csrf behaviour by using @Profile annotations.
Current Behavior
Documentation for CORS states:
By default if a
CorsConfigurationSourceBean is found, it will be used to create aCorsWebFilter
CSRF is on the hand enabled by default, and can be disabled by:
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
// ...
.csrf(csrf ->
csrf.disabled()
);
return http.build();
}
Context
I usually develop a react app which is running on localhost:3000 and i have a spring backend running on localhost:8080. Since the webpage is not served by the spring application, the frontend will not get a csrf cookie. But when running in production i serve the webpage from the spring backend.
So when developing locally i disable CSRF and CORS. CORS is easy to disable, just annotate a CorsConfigurationSource bean with a @Profile("!prod"), while CSRF is not configured the same way, so i had to define a boolean in application.properties, and have an if statement encapsulating a http.cors().disable().
Comment From: jgrandja
@Tandolf Have you considered this configuration for your scenario:
@Bean
@Profile("!Prod")
SecurityWebFilterChain configure(ServerHttpSecurity http) {
// Disable csrf
....
}
@Bean
@Profile("Prod")
SecurityWebFilterChain configure(ServerHttpSecurity http) {
....
}
This would work without needing a CsrfConfigurationSource @Bean.
Comment From: Toerktumlare
i could ofc declare the security chain in a private method and return and add on the csrf, i was more thinking of trying to have a concise API, since the configuration is so different for the both parts.
Comment From: jgrandja
@Tandolf
i was more thinking of trying to have a concise API, since the configuration is so different for the both parts
ServerHttpSecurity is the main API for configuring security so I would recommend using this directly as it gives you full control. And it's quite common to define more than one ServerHttpSecurity, depending on your setup, eg. dev, test, prod, user-facing, admin-facing, etc..
I'm going to close this issue as the recommended way is to directly configure security via ServerHttpSecurity.