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.
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; } }
Avoid using the following incorrect solutions:
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!