当 Spring Security 添加到现有项目时,出现“401 No 'Access-Control-Allow-所请求的资源上存在 Origin' 标头”遇到错误。出现这种情况是因为 Access-Control-Allow-Origin 标头未添加到响应中。
要解决此问题,从 Spring Security 4.1 开始,启用 CORS 支持的正确方法是如下:
在 WebConfig 中:
@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"); } }
在 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; } }
避免使用以下不正确的解决方案:
以上是如何修复 Spring Security 中的'401 No \'Access-Control-Allow-Origin\' header”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!