【发布时间】:2020-07-17 06:27:25
【问题描述】:
我有一个使用 Spring Boot 实现的应用程序,我使用 Spring Security 进行身份验证。我已经有了“基于令牌”的身份验证,客户端需要检索令牌,然后使用该令牌在后续请求中进行身份验证。
我想对此进行增强,以便可以将令牌限制为特定的主机名,这样只能用于来自该主机的请求。这类似于 google maps API 使用其 API 密钥所做的事情,可以通过 IP 或主机名来限制它们。
这是我为尝试检索请求的主机名而实现的代码
public String getClientHostName(HttpServletRequest request) {
String hostName = null;
// get the request's IP address
String clientAddress = httpRequest.getRemoteAddr();
String xfHeader = httpRequest.getHeader("X-Forwarded-For");
if (xfHeader != null) {
clientAddress = xfHeader.split(",")[0];
}
// try to resolve the host name from the IP address
try {
InetAddress address = InetAddress.getByName(clientAddress);
hostName = address.getHostName();
} catch (UnknownHostException e) {
logger.error("Failed to get the host name from the request's remote address. ", e);
}
return hostName;
}
我现在有 2 个问题:
此代码并不总是能够检索主机名。有时它只返回 IP 地址。我知道这可能归结为IP spoofing check the InetAddress class does。
在测试来自不同主机的请求时,我并不总是得到我期望的 IP 地址。我经常得到另一个转发请求的主机的IP(我认为可以通过检查“X-Forwarded-For”来解决)。这让我想知道如何检索真正发起请求的主机的 IP。
是否有可靠的方法来检查请求发起者的主机名?
【问题讨论】:
标签: java spring-boot authentication spring-security cdn