Home >Java >javaTutorial >How to Fix the \'401 No \'Access-Control-Allow-Origin\' header\' Error in Spring Security?

How to Fix the \'401 No \'Access-Control-Allow-Origin\' header\' Error in Spring Security?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-31 16:08:02708browse

How to Fix the

Spring Security CORS Filter

Problem

When Spring Security is added to an existing project, a "401 No 'Access-Control-Allow-Origin' header is present on the requested resource" error is encountered. This occurs because an Access-Control-Allow-Origin header is not added to the response.

Solution

To resolve this issue, since Spring Security 4.1, the proper way to enable CORS support is as follows:

In WebConfig:

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH");
    }
}

In SecurityConfig:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.csrf().disable();
        http.cors();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(ImmutableList.of("*"));
        configuration.setAllowedMethods(ImmutableList.of("HEAD",
                "GET", "POST", "PUT", "DELETE", "PATCH"));
        configuration.setAllowCredentials(true);
        configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

Incorrect Solutions

Avoid using the following incorrect solutions:

  • http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll();
  • web.ignoring().antMatchers(HttpMethod.OPTIONS);

The above is the detailed content of How to Fix the '401 No 'Access-Control-Allow-Origin' header' Error in 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