Search code examples
spring-securitycsrf

On what basis requireCsrfProtectionMatcher is initialised in csrfFilter


The CsrfFilter has a validation

if (!this.requireCsrfProtectionMatcher.matches(request)) {
            filterChain.doFilter(request, response);
            return;
        }

in the above snippet, this.requireCsrfProtectionMatcher is getting initialised to AndRequestMatcher. But I want to use only DefaultRequiresCsrfMatcher. Can anyone please provide more information about this? My security Configuration

 @Override
    protected void configure(HttpSecurity http) throws Exception {
          http.csrf().and().
          cors().and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/rest/open/**").permitAll()
            .and().authorizeRequests()
            .antMatchers("/**").authenticated()
            .anyRequest().permitAll()
            .and()
            .oauth2ResourceServer()
            .jwt()
            .jwtAuthenticationConverter(getJwtAuthoritiesConverter());
            

    }

Solution

  • The requireCsrfProtectionMatcher is being initialized with AndRequestMatcher because you are using oauth2ResourceServer().jwt().

    The oauth2ResourceServer DSL tells the CsrfFilter to ignore requests which contain a Bearer token. You can check it in the source code.

    Since the JWT authentication is stateless, you would not need a CSRF token in the request.