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