HttpServletRequest - how to obtain the referring URL?
It's available in the HTTP referer
header. You can get it in a servlet as follows:
String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.
You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.
For the interested, background about the misspelling can be found in Wikipedia.
Get Referer URL in Spring MVC
It's available as HTTP request header with the name referer
(yes, with the misspelling which should have been referrer
).
String referrer = request.getHeader("referer");
// ...
Here the request
is the HttpServletRequest
which is available in Spring beans in several ways, among others by an @AutoWired
.
Please keep in mind that this is a client-controlled value which can easily be spoofed/omitted by the client.
Java get referer URI?
You want something like this?
String refererURI = new URI(request.getHeader("referer")).getPath();
Get beautified URL from HttpServletRequest
When the servlet based URL rewrite engine uses under the covers RequestDispatcher#forward()
to forward an incoming friendly-URL request to the desired resource, then you can use request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI)
to find out the original request URI.
String originalRequestURI = request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
As you're already using OmniFaces, you can use Servlets#getRequestURI()
to automatically detect it and return it when present, else fall back to the default HttpServletRequest#getRequestURI()
.
String requestURI = Servlets.getRequestURI(request);
HttpServletRequest getHeader(HttpHeaders.REFERER) returns NULL
You can get original URI as
String originalUri = request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);
Similar query on stack web.xml 404 redirect to servlet, how to get the original URI?
HttpServletRequest, csrf check for referrer header
This was actually a bit harder than I thought so I thought I'd share what I came up with. The code could be optimized - there are too many if
statements but it looks like you are coming from a different language so I tried to make it fairly straight forward. Additionally, there are probably some error conditions I missed but it should be close.
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebFilter
public class RefererFilter implements Filter {
private static final String PATH = "/abc/sso?module=console";
// the domains that you will accept a referrer from
private static final List<String> acceptableDomains = Arrays.asList("google.com", "mydomain.com");
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// unused in this application
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
String refererHeader = request.getHeader("referer");
// no need to continue if the header is missing
if (refererHeader == null) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// parse the given referrer
URL refererURL = new URL(refererHeader);
// split the host name by the '.' character (but quote that as it is a regex special char)
String[] hostParts = refererURL.getHost().split(Pattern.quote("."));
if (hostParts.length == 1) { // then we have something like "localhost"
if (!acceptableDomains.contains(hostParts[0])) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
} else if (hostParts.length >= 2) { // handle domain.tld, www.domain.tld, and net1.net2.domain.tld
if (!acceptableDomains.contains(hostParts[hostParts.length - 2] + "." + hostParts[hostParts.length - 1])) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
}
// if we've gotten this far then the domain is ok, how about the path and query?
if( !(refererURL.getPath() + "?" + refererURL.getQuery()).equals(PATH) ) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
// all tests pass - continue filter chain
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
// unused in this implementation
}
}
How to redirect to the referrer in a filter?
In the doFilter()
method, you need to cast the obtained ServletResponse
argument to HttpServletResponse
and then call the sendRedirect()
method on it. The page where the request originated can be obtained by the referer
request header (yes, with the legendaric misspelling) which can be obtained by HttpServletRequest#getHeader()
after casting it from the ServletRequest
argument.
if (userHasPermission) {
chain.doFilter(request, response);
} else {
String referrer = ((HttpServletRequest) request).getHeader("referer");
((HttpServletResponse) response).sendRedirect(referrer);
}
Please note that the referrer is a client-controlled value and thus this can be spoofed or even removed. You'd like to add conditional checks on the obtained value and when absent or invalid, redirect to the main page instead or somewhere else.
See also:
- Our
servlet-filters
wiki page (you can get this page by putting your mouse above the tag below the question until a popbox shows and then click the info link on the popbox)
How to use request.getHeader(Referer)
You shouldn't rely on Referer
for the logic of your application, since sending Referer
can be blocked by firewalls or browser configuration.
Consider passing return URL as a parameter instead: http://mainsite.com/shoppingCart?returnTo=http%3a%2f%2fminisite.com%2foriginalPage
.
Also make sure that returnTo
points to your site to avoid possible security problems.
glassfish servlet: how to know the referer url? if possible
You can read the Referer header
of the request and get the value by using request.getHeader("Referer");
Related Topics
Final Keyword in Method Parameters
Split List into Multiple Lists with Fixed Number of Elements in Java 8
How to Connect to Postgres Db Due to the Authentication Type 10 Is Not Supported
Java.Sql.Sqlexception: Exhausted Resultset
Java Simpledateformat for Time Zone with a Colon Separator
Java: How to Access Methods from Another Class
How to Run a Class in a War from the Command Line
Order of Loading Jar Files from Lib Directory
Combine Multiple Collections into a Single Logical Collection
Calculating All of the Subsets of a Set of Numbers
JSONobject:Why JSONobject Changing the Order of Attributes
Is There a 'Block Until Condition Becomes True' Function in Java
How to Add a New Line of Text to an Existing File in Java
Can You Explain the Httpurlconnection Connection Process