Spring Security CORS 过滤器:排除“不存在‘Access-Control-Allow-Origin’标头”
说明
将 Spring Security 添加到现有项目可能会在跨源资源共享 (CORS) 请求期间触发“不存在‘Access-Control-Allow-Origin’标头”错误。出现此错误的原因是请求中未添加 Access-Control-Allow-Origin 响应标头。
解决方案
方法 1:
更新您的代码以使用 Spring Security 的内置 CORS 支持。将以下配置添加到您的应用程序中:
<code class="java">@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH"); } }</code>
方法 2:
如果您想更好地控制 CORS 配置,请使用以下方法:
<code class="java">@Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { 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; } }</code>
附加说明:
以上是添加 Spring Security 后,为什么我会收到“不存在“Access-Control-Allow-Origin”标头”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!