Spring CORS 错误:响应中的“Access-Control-Allow-Credentials”标头为“”,当请求的凭据模式为“include”时,该标头必须为“true”

问题描述 投票:0回答:1

我正在使用

org.springframework.boot:spring-boot-starter-web:2.5.5
spring-security
部署为 openshift 中的后端 Spring Boot 应用程序作为容器。还有一个托管在另一个容器上的 Angular 11.0.1 前端应用程序。在从前端应用程序到后端的测试过程中,我收到 CORS 错误。以下是浏览器控制台中的错误消息

Access to XMLHttpRequest at 'https://backend.apps.ocpa.company.com/app/user/config' from origin 'https://frontend.apps.ocpa.company.com' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

我在 MvcConfig 类中启用了 cors 配置,如下所示

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    @Value("${cors.allowed-origins:*}")
    String allowedOrigins;


    @Override
    public void addCorsMappings(CorsRegistry registry) {

        registry.addMapping("/**")
                .allowedOrigins(allowedOrigins)
                .allowCredentials(true);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
    }

}

我仍然收到此错误

spring spring-mvc security spring-security cors
1个回答
0
投票

我通过在“public class WebSecurityConfig extends WebSecurityConfigurerAdapter”中添加以下代码片段来解决它

 @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()......
    }



@Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        System.out.println("corsConfig Source - allowedOrigins " + allowedOrigins);
        configuration.setAllowedOrigins(Arrays.asList(allowedOrigins));

        ArrayList<String> headersList = new ArrayList<String>();
        headersList.add("Authorization");
        headersList.add("Cache-Control");
        headersList.add("Access-Control-Allow-Credentials");
        configuration.setAllowedHeaders(headersList);

        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
© www.soinside.com 2019 - 2024. All rights reserved.