Search code examples
springspring-securitycsrfcsrf-token

Does spring-security automatically disable CSRF when Authorization header (bearer jwt token) is used?


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:

  1. If I don't pass a JWT
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
  1. But If I pass the JWT tokenin authorization header like below request, then Spring doesn't complain about CSRF.
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


Solution

  • 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:

    1. This excellent answer to a related Question https://stackoverflow.com/a/71782433/4627552

    2. Discussion on Spring security issues page https://github.com/spring-projects/spring-security/issues/8668