I have configured by spring boot application to work as an oauth2 resource server which expects JWT tokens in every request. Im seeing some behaviour with Spring Security such as below:
curl -X POST --data '{"somejson":"some data"}' --header "Content-Type: application/json" http://localhost:8080
The API gives a response like:
An expected CSRF token cannot be found
curl -X POST --data '{"somejson":"some data"}' --header "Content-Type: application/json" --header "Authorization: Bearer JWTfirstpart.secondpart.thirdpart" http://localhost:8080
Does spring security automatically disable the CSRF check when the auth header is present?
My Spring security configuration looks like this
SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http
.authorizeExchange(exchanges -> exchanges
.anyExchange().authenticated()
)
.oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt);
return http.build();
}
I constructed the configuration as per the spring docs here https://docs.spring.io/spring-security/reference/reactive/oauth2/resource-server/jwt.html
This behaviour is because of OAuth2ResourceServerConfigurer#registerDefaultCsrfOverride
. It doesn't apply the CSRF token validation to requests that contain a Bearer token, by using the BearerTokenRequestMatcher.
This is why, when I sent a JWT bearer token, no csrf check is applied, but when I don't send JWT bearer token, request fails with "CSRF token missing" error.
Sources:
This excellent answer to a related Question https://stackoverflow.com/a/71782433/4627552
Discussion on Spring security issues page https://github.com/spring-projects/spring-security/issues/8668