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

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

Linda Hamilton
Release: 2024-11-27 00:17:10
Original
277 people have browsed it

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

CORS Configuration in Spring Boot and Spring Security

When using Spring Boot and Spring Security while supporting CORS, certain configuration issues can arise, leading to unexpected results.

One such issue is encountered when making a GET request with XMLHttpRequest and using CORS support, where a 200 status code is returned despite incorrect authentication credentials. This behavior introduces discrepancies in handling HTTP status codes on the front-end.

Solution

To resolve this problem, it is crucial to explicitly enable CORS support in Spring Security. This is accomplished by setting up CORS in Spring Security, which enables it to leverage Spring MVC CORS configuration.

For applications using @CrossOrigin annotations at the controller level, simply enabling Spring Security CORS support will suffice. The code below demonstrates this:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}
Copy after login

For users opting for global CORS configuration, it is necessary to define 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;
    }
}
Copy after login

By utilizing this approach, CORS support is effectively enabled in Spring Boot and Spring Security, addressing the issue where the proper CORS headers were not being added during authentication checks. Refer to the official Spring Security documentation on CORS for further details.

The above is the detailed content of How to Properly Configure CORS in Spring Boot with Spring Security?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template