I have a servlet, is it possible to check if a request came from a specific domain, say "example.com"?
public abstract class MyServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
if (didOriginateFrom("example.com", req)) {
// ok to process
}
}
}
I have one server that will offload some work to a secondary server (above), just want to make sure it only process requests that come from my primary server,
Thanks
The below methods give you the information of the client host machine which has made the request.
HttpServletRequest.getRemoteAddr()
HttpServletRequest.getRemoteHost()
Here is the code you are looking for:
boolean didOriginateFrom(Sting host, HttpServletRequest req) {
return req.getRemoteHost().contains(host);
}
Both the above methods gives information about the client or the last proxy address that sent the request.
Some servers might return the original client address though the request has come through several proxies. Proxies send the address of the immediate client to the server by adding X-Forwarded-For header. Thus some servers might process the X-Forwarded-For header values and return the original client address.
Here is how the X-Forwarded-For request header might look
X-Forwarded-For : originalclient, proxy1, proxy2, lastproxy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With