首页 > 解决方案 > 即使在 Springboot 项目上使用 @CrossOrigin 注释定义后,跨域白名单 IP 也未应用

问题描述

我关注了https://spring.io/guides/gs/rest-service-cors/并在我的 API 端点之一中添加了一个像这样的随机 IP -

@Produces(MediaType.APPLICATION_JSON)
    @CrossOrigin(origins = "116.206.111.61")
    public XAmount getBalance(@Context SecurityContext security) {
        String customer = null;
        .. API code goes here ..
        }
    }

我现在只希望通过这个 API 接受来自这个 IP 的请求,所以期待来自我的客户端的请求失败。然而,这并没有发生。

我可以使用 IP 向另一台服务器请求,比如说 IP1。这是请求日志,在进行更改后 -

2020-06-05 09:36:57,407 283453 [XNIO-3 task-1] INFO  [LoggingFilter.java:155] - 1 * Server has received a request on thread XNIO-3 task-1
1 > GET http://sandbox-server.com/service/v2/api
1 > Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
1 > Accept-Encoding: gzip
1 > Authorization: Bearer <token>
1 > Cache-Control: no-cache
1 > Connection: close
1 > Content-Type: application/x-www-form-urlencoded; charset=UTF-8
1 > Host: <domain of API>
1 > Pragma: no-cache
1 > User-Agent: Java/1.7.0_79
1 > X-Forwarded-For: <IP - source server from which API call is made>, <some other IP>, <yet another IP>, <yet another IP>
1 > X-Forwarded-Host: <domain of API>
1 > X-Forwarded-Port: 443
1 > X-Forwarded-Proto: https
1 > X-Forwarded-Server: <domain of API>

可以看出,我在 X-Forwarded-For 下列出的第一个 IP 中获取了发出请求的服务器的 IP。其余的 IP 似乎是路由它的服务器。我在 @CrossOrigin -> origins 中添加了一个不同的 IP,但请求仍然可以正常工作。还需要做什么?

顺便说一下,这是我们的沙盒服务器。我在生产中检查了相同的 API 日志,但没有进行此更改。在那里,我没有看到 X-Forwarded-For。相反,我看到 Client-IP 标头 -

2019-06-13 07:04:13,357 248327 [XNIO-3 task-17] INFO  [LoggingFilter.java:155] - 47 * Server has received a request on thread XNIO-3 task-17
47 > GET domain-of-api/service/v2/api
47 > Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
47 > Accept-Encoding: gzip
47 > Authorization: Bearer <token>
47 > Cache-Control: no-cache
47 > Client-IP: <IP of an internal server via which traffic is routed>
47 > Connection: Close
47 > Content-Type: application/x-www-form-urlencoded; charset=UTF-8
47 > Host: <domain of API>
47 > Pragma: no-cache
47 > User-Agent: Java/1.7.0_111

无论我做出什么改变,我都需要能够在沙盒上进行测试。

标签: javaspring-bootcross-domainaccess-controlclientip

解决方案


推荐阅读