Giovanni Silva
Giovanni Silva

Giovanni Silva

How to configure CORS with spring security

Giovanni Silva's photo
Giovanni Silva
·Sep 21, 2019·

1 min read

If you use spring security with Angular frontend, you have to properly configure Cross Site Script and Cross-Site Request Forgery CSRF in orther to make request to your backend.

To do so in a development environment you may use the following configuration:

import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter

@Configuration
class MvcConfig {
  @Bean
  fun corsFilter(): CorsFilter {
    val source = UrlBasedCorsConfigurationSource()
    val config = CorsConfiguration()
    config.allowCredentials = true
    config.addAllowedOrigin("*")
    config.addAllowedHeader("*")
    config.addAllowedMethod("OPTIONS")
    config.addAllowedMethod("GET")
    config.addAllowedMethod("POST")
    config.addAllowedMethod("PUT")
    config.addAllowedMethod("DELETE")
    source.registerCorsConfiguration("/**", config)
    return CorsFilter(source)
  }
}

And in your spring security http config:

  @Throws(Exception::class)
  override fun configure(http: HttpSecurity) {
    super.configure(http)
    http
      .csrf().disable()
      .cors()
      .and()
      .authorizeRequests()
      .anyRequest().permitAll()
  }

In a production environment you will configure CORS accordingly, I recomend the use of spring profile configuration you could inject configuration values or create another bean that is enabled only if a property is enabled with @ConditionalOnProperty(prefix = "app.cors.production", value = "true")

To enable CSRF you need the line .csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).

Angular will add the X-XSRF-TOKEN header if the application reside in the same server, this should be enought to work when you deploy.

You could check the current profile with the Environment autowired class and enable CSRF in production

 
Share this