当Host头存在时如何确定请求的真实serverPort [重复]

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

这个问题在这里已有答案:

我有一个启动管理端点的Spring启动应用程序。这意味着应用程序在端口8080上启动,管理端点在端口8081上可用。

使用Spring安全性保护应用程序,但是,无需身份验证即可访问管理端点。所以我添加了一个请求匹配器,用于评估服务器端口(使用request.getServerPort())以忽略对端口8081上的管理端点的所有请求。

现在碰巧当存在Host头时,此头的端口在request.getServerPort()中返回,而不是真实的服务器端口。

这意味着我可以使用带有端口8081的Host标头访问应用程序并绕过Spring Security !?

清晰的例子:

curl localhost:8080
returns 401 (unauthorized, that's correct)

curl localhost:8081/health
returns 200 (found)

curl -H "Host: localhost:8081" localhost:8080
returns 200 (wtf?) - because request.getServerPort() == 8081

curl -H "Host: localhost:8080" localhost:8081/health
returns 401 - because request.getServerPort() == 8080

问题是:如何确定应用程序接收请求的真实端口?

java http spring-security servlet-3.0
1个回答
1
投票
ServletRequest#getLocalName() returns local hostname.
ServletRequest#getLocalAddr() returns local IP.
ServletRequest#getLocalPort() returns local port.

为了更加清晰,请参阅:Get Application Server name or ip and port in Java

© www.soinside.com 2019 - 2024. All rights reserved.