Handling CORS with Spring Boot Spring Security
When using Spring Boot with Spring Security and CORS support, unexpected behavior can arise. By default, CORS preflight requests may be blocked by Spring Security before reaching Spring MVC.
Configuration Options:
To address this, explicitly enable CORS support in Spring Security by adding the following code to the HttpSecurity configuration:
@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and()... } }
Global CORS Configuration:
Alternatively, you can define a global CORS configuration by declaring a CorsConfigurationSource bean:
@EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.cors().and()... } @Bean CorsConfigurationSource corsConfigurationSource() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues()); return source; } }
Addressing CORS Concerns
This approach replaces the previously recommended filter-based approach. For more information, refer to the CORS section of the Spring Security documentation.
Known Issues and Workarounds
If these configurations do not resolve the issue, consider the following workaround:
[Github Issue 5834](https://github.com/spring-projects/spring-boot/issues/5834) provides a potential solution.
The above is the detailed content of How to Properly Configure CORS with Spring Boot and Spring Security?. For more information, please follow other related articles on the PHP Chinese website!