
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!
What are the servers that are exempt from registration?
What is topology optimization
What are the new features of Hongmeng OS 3.0?
The difference between null and NULL in c language
Check disk space in linux
Unknown error 3004 solution
Cost-effectiveness analysis of learning python, java and c++
How to play video with python