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中文網其他相關文章!