【问题标题】:Multiple ips in Access-Control-Allow-Origin not workingAccess-Control-Allow-Origin 中的多个 ip 不起作用
【发布时间】:2019-02-01 16:43:45
【问题描述】:

我的 API 服务器在端口 8090 上的 Spring Boot 应用程序中运行,而前端应用程序在 Angular 6 中运行。 一切正常,直到我在 Access-Control-Allow-Origin 标头中有单个 IP。

现在 API 被运行在不同端口(80 和 7000)上的 2 个不同字体端应用程序使用。我在 Access-Control-Allow-Origin 标头中添加了两个 IP,但它不起作用

根据this,我们可以有多个用逗号分隔的 cors 来源

详情:

Request:

Accept: /
Accept-Encoding: gzip, deflate
Accept-Language: en-IN,en-GB;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: content-type,x-auth
Access-Control-Request-Method: GET
Cache-Control: no-cache
Connection: keep-alive
Host: 192.168.1.10:8090
Origin: http://192.168.1.10:7000
Pragma: no-cache
Referer: http://192.168.1.10:7000/user/dashboard

Response:

Access-Control-Allow-Headers: X-Auth,Origin,X-Requested-With,Content-Type,Accept,X-Forwarded-For
Access-Control-Allow-Methods: GET,POST,OPTIONS,PUT,DELETE
Access-Control-Allow-Origin: http://192.168.1.10,http://192.168.1.10:7000
Access-Control-Expose-Headers: X-Auth
Content-Length: 0
Date: Fri, 01 Feb 2019 05:54:29 GMT

Error: 

Access to XMLHttpRequest at 'http://192.168.1.10:8090/api/patient/logout' from origin 'http://192.168.1.10:7000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values 'http://192.168.1.10,http://192.168.1.10:7000', but only one is allowed.

【问题讨论】:

  • Access-Control-Allow-Origin: http://192.168.1.10,http://192.168.1.10:7000 是无效的语法。如果您想允许多个来源,那么您需要让服务器代码以编程/动态方式将标头的值设置为单个来源,而不是在标头中硬编码原始值。该代码需要检查 Origin 请求标头的值,如果该 Origin 请求的值在您要允许的源列表中,则将 Access-Control-Allow-Origin 响应标头设置为相同的值。跨度>

标签: angularjs spring-boot cors


【解决方案1】:

在大多数情况下,this 是有效的,但是当您的应用程序中有请求过滤器时,您需要为此编写代码:

    String origin = request.getHeader("Origin");
    if (StringUtils.isNoneBlank(origin)) {
        if (applicationSettings.getAllowedOrigins().contains("*") || applicationSettings.getAllowedOrigins().contains(origin)) {
            response.setHeader("Access-Control-Allow-Origin", origin);
        }
    } else {
        response.setHeader("Access-Control-Allow-Origin", "*");
    }

【讨论】:

    【解决方案2】:

    下面应该可以在 spring boot 端允许多个来源:

    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://192.168.1.10:8090","http://192.168.1.10:7000");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-16
      • 2011-09-13
      • 2021-01-01
      • 2017-08-29
      • 2015-05-02
      • 2013-10-27
      • 2015-06-17
      • 2018-07-18
      • 2017-06-27
      相关资源
      最近更新 更多