In my JSP webapp, i want to validate that a user is coming from a specific page of mine, http://myapplication.com/foo.jsp
. On the page doing the checking, I could do:
String ref = request.getHeader("referer");
Then compare ref
to http://myapplication.com/foo.jsp
However, this validation can be easily spoofed. What are some other techniques to verify that a client is coming from an expected URL?
I imagine this has come up before in SO. Thanks
PR
Let the preprocessing servlet of the first JSP generate an unique token.
String token = UUID.randomUUID().toString();
Store this in session
session.setAttribute("token", token);
Pass it as hidden input value of the form
<input type="hidden" name="token" value="${token}" />
or as a request parameter of the link when you're using links instead of forms
<a href="second.jsp?token=${token}">link</a>
Let the preprocessing servlet of the second JSP compare it with the one in the session
String token = (String) session.getAttribute("token");
session.removeAttribute("token");
if (token != null && token.equals(request.getParameter("token"))) {
// Valid, continue requesst.
} else {
// Invalid, block request.
}
That was the basic concept which assumes a single page-to-page conversation. To cover multiple browser pages/tabs you'd like to use Set<String>
or maybe Map<String, Set<String>>
as token instead (with URIs as keys and tokens as values).