简体   繁体   中英

Spring Security - Token authentication with request host name

I have an application implemented with Spring Boot, where I use Spring Security for authentication. I already have "token based" authentication in place, where clients are required to retrieve a token, and then use that token to authenticate in subsequent requests.

I would like to enhance this so that a token could be restricted to a specific hostname, so that is can only be used for requests from that host. This is similar to what the google maps API does with its API keys, where it is possible to restrict them by IP or host name.

Here is the code I have implemented to try to retrieve the request's host name

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

I have 2 issues right now:

  1. This code does not always manage to retrieve the hostname. Sometimes it just returns the IP address. I understand this may be down to some IP spoofing check the InetAddress class does .

  2. When testing requests from different hosts, I do not always get the IP address I am expecting. I often get the IP of another host that is forwarding the request (which I thought would be solved by checking "X-Forwarded-For"). This makes me wonder how to even retrieve the IP of the host that is the real originator of the request.

Is there a reliable way to check the host name of the originator of a request?

have you tried getting hostname by String referrer = request.getHeader("referer"); ?

Also, on client side also you can add a snippet to find out the hostname in the headers.

您可以通过添加片段来获取服务器端的主机名。

Or you can provide below code to be added on client side and on server you can read the value of domain which will return hostname

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM