簡體   English   中英

Spring 安全性 - 使用請求主機名進行令牌身份驗證

[英]Spring Security - Token authentication with request host name

我有一個使用 Spring Boot 實現的應用程序,我使用 Spring Security 進行身份驗證。 我已經有了“基於令牌”的身份驗證,客戶端需要檢索令牌,然后使用該令牌在后續請求中進行身份驗證。

我想對此進行增強,以便可以將令牌限制為特定的主機名,以便只能用於來自該主機的請求。 這類似於谷歌地圖 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;
}

我現在有兩個問題:

  1. 此代碼並不總是設法檢索主機名。 有時它只返回 IP 地址。 我知道這可能是由於一些IP 欺騙檢查 InetAddress class 所做的

  2. 在測試來自不同主機的請求時,我並不總是得到我期望的 IP 地址。 我經常得到另一個正在轉發請求的主機的 IP(我認為可以通過檢查“X-Forwarded-For”來解決)。 這讓我想知道如何甚至檢索作為請求的真正發起者的主機的 IP。

是否有可靠的方法來檢查請求發起者的主機名?

您是否嘗試過通過String referrer = request.getHeader("referer");獲取主機名? ?

此外,在客戶端,您還可以添加一個片段來找出標題中的主機名。

您可以通過添加片段來獲取服務器端的主機名。

或者您可以提供以下代碼以添加到客戶端和服務器上,您可以讀取將返回主機名的域的值

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM