CORS spring security filter vs WebMvcConfigurer.addCorsMappings

Viewed 1395

What the difference of cors() filter in configure method of WebSecurityConfigurerAdapter class and create bean of WebMvcConfigurer and override addCorsMappings method? when we use of which? can anyone explain it?

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000");
        }
    };
}

vs

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
                .csrf().disable()
                .authorizeRequests()
                .mvcMatchers("/rest/**").authenticated()
                .anyRequest().permitAll()
                .and()
          .oauth2ResourceServer().jwt().jwtAuthenticationConverter(this.jwtAuthenticationConverter())
        ;
    }

}

1 Answers

Spring Web MVC

WebMvcConfigurer is part of the Spring Web MVC library. Configuring CORS with addCorsMappings adds CORS to all URLs which are handled by Spring Web MVC, see 1.7.2. Processing:

Spring MVC HandlerMapping implementations provide built-in support for CORS. After successfully mapping a request to a handler, HandlerMapping implementations check the CORS configuration for the given request and handler and take further actions.

You have to use it, if no Spring Security is used (non secured applications) or not all Spring Web MVC URLs are handled by Spring Security (some ULRs are unsecured).

You can't use it for non Spring Web MVC URLs like JSF, Servlet, JAX-WS, JAX-RS, ...

Spring Security

WebSecurityConfigurerAdapter is part of the Spring Security library. Configuring CORS with cors() adds CORS to all URLs which are handled by Spring Security, see 15.8. CORS:

Spring Framework provides first class support for CORS. CORS must be processed before Spring Security because the pre-flight request will not contain any cookies (i.e. the JSESSIONID). If the request does not contain any cookies and Spring Security is first, the request will determine the user is not authenticated (since there are no cookies in the request) and reject it.

The easiest way to ensure that CORS is handled first is to use the CorsFilter.

You have to use it, if you use Spring Security.

If you are using Spring Web MVC and Spring Security together you can share the configuration, see 15.8. CORS:

If you are using Spring MVC’s CORS support, you can omit specifying the CorsConfigurationSource and Spring Security will leverage the CORS configuration provided to Spring MVC.

Related