繁体   English   中英

启用跨源请求 Spring Boot

[英]Enabling Cross Origin Requests Spring Boot

我正在开发一个应用程序,它由一个用 Spring Boot 开发的后端应用程序和一个用 Angular 8 开发的前端应用程序组成。现在我想启用 Cross Origin 让前端调用后端的 API。
根据有关 CORSSpring 文档,我编写了以下配置类:

@EnableWebSecurity
public class WebConfig extends WebSecurityConfigurerAdapter {

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

    @Bean
    CorsConfigurationSource corsConfigurationSource()
    {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

第一次尝试是将 AllowedOrigins 设置为Arrays.asList("*")


当我从 Angular 应用程序调用 api /dinners/ingredients ,我在控制台中发现了以下错误:

从源“ http://localhost:4200 ”访问“ http://localhost:8081/dinners/ingredients?page=0&pageSize=10 ”的 XMLHttpRequest 已被 CORS 策略阻止:无“访问控制允许源” ' 请求的资源上存在标头。
GET http://localhost:8081/ dinners /ingredients?page=0&pageSize=10 net::ERR_FAILED


我在后端应用程序的配置中遗漏了什么吗? 我在 Postman 的标头响应中没有看到“Access-Control-Allow-Origin”标头:
邮差

您发布的文档是指 spring 安全 4.2(您可以在您提供的 url 中看到),如果您查看最新的 spring 安全文档(5.x),您将看到要配置的标准实现的 cors 过滤器对于外部 bean,您需要调用withDefaults()方法。

Cors 配置 spring 5.x

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // by default uses a Bean by the name of corsConfigurationSource
            .cors(withDefaults()) // <------ this part
            ...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

如果您正在寻找仅出于开发目的启用 CORS,那么您应该考虑使用Angular Proxy

https://angular.io/guide/build#proxying-to-a-backend-server

注意:启用 CORS 可能会使您的应用程序暴露在漏洞中,请非常具体地在何处启用 CORS。

您需要在请求中添加一个标头,如下所示:

来源:“somerandomstring”

一旦你这样做,springboot 就会开始向客户端发送 cors 标头。 这看起来像是 springbot 中的一个错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM