Home >Web Front-end >JS Tutorial >How to Properly Configure CORS with Spring Boot and Spring Security?

How to Properly Configure CORS with Spring Boot and Spring Security?

DDD
DDDOriginal
2024-11-28 17:04:10696browse

How to Properly Configure CORS with Spring Boot and Spring Security?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn