【问题标题】:Spring Security - Token authentication with request host nameSpring Security - 使用请求主机名进行令牌认证
【发布时间】: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 个问题:

  1. 此代码并不总是能够检索主机名。有时它只返回 IP 地址。我知道这可能归结为IP spoofing check the InetAddress class does

  2. 在测试来自不同主机的请求时,我并不总是得到我期望的 IP 地址。我经常得到另一个转发请求的主机的IP(我认为可以通过检查“X-Forwarded-For”来解决)。这让我想知道如何检索真正发起请求的主机的 IP。

是否有可靠的方法来检查请求发起者的主机名?

【问题讨论】:

    标签: java spring-boot authentication spring-security cdn


    【解决方案1】:

    您是否尝试过通过String referrer = request.getHeader("referer"); 获取主机名?

    另外,在客户端,您也可以添加一个 sn-p 来找出标头中的主机名。

    或者您可以提供以下代码添加到客户端和服务器上,您可以读取将返回主机名的域值

    <input type="button" value="Register" onClick="call()"/>
    <script>
    function call(){
        var domain=window.location.hostname;
        window.open('http://<your-hostname>/register?domain='+domain,'_self');
    }
    </script>
    

    【讨论】:

    • 感谢您的回答。我担心这个解决方案可能太弱了。如果是客户端明确指定主机,它很容易欺骗它。例如:如果令牌 A 只能从主机 A 使用,则从主机 B 调用的客户端仍然可以通过简单地在请求标头中指定主机 A 来使用该令牌。
    猜你喜欢
    • 2013-08-10
    • 2015-10-12
    • 2014-11-05
    • 2016-04-21
    • 2014-04-04
    • 2019-12-06
    • 2013-06-12
    • 2012-03-13
    • 2013-04-11
    相关资源
    最近更新 更多