Who is calling my HttpServletRequest?

I have a jsp containing a jquery post for a servlet on my tomcat server that creates an HttpServletRequest . I would like to make sure that only my jsp calls are processed for my servlet, and any requests originating from a source other than my jsp are ignored. Is there a guaranteed way to see which link page calls my server? I read that using request.getHeader("referer") can be tricked, so I know that I can not rely on this.

+4
source share
4 answers

Create a unique string as a token, save it in the session and paste it as a hidden input value in the form of a POST JSP, and finally check the servlet if the token is valid.

Basically:

When creating a session (e.g. HttpSessionListener#sessionCreated() ):

 Set<String> tokens = new HashSet<String>(); event.getSession().setAttribute("tokens", tokens); 

When pre-processing a JSP request (for example, HttpServlet#doGet() ):

 String token = UUID.randomUUID().toString(); Set<String> tokens = (Set<String>) request.getSession().getAttribute("tokens"); tokens.add(token); request.setAttribute("token", token); 

When processing the JSP itself:

 <input type="hidden" name="token" value="${token}" /> 

When post-processing the submit form (in HttpServlet#doPost() , for example):

 String token = request.getParameter("token"); Set<String> tokens = (Set<String>) request.getSession().getAttribute("tokens"); if (!tokens.remove(token)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // ... 

Of course, I assume that your jQuery.post() functions are written unobtrusively, as in $.post(form.action, form.serialize(), callback) , so that it mimics exactly the usual synchronous request (in other words, your forms work fine with disabled JS).

+5
source

You can create an arbitrary cookie for your jsp, then add it to your POST form and accept only requests with the correct cookie value.

+1
source

You can make a secure token for your JSP and include it in your Ajax call on the Servlet, where you can check it. It also does not guarantee that the Ajax call is made using the browser and your Javascript, but it at least requires someone to get a secure token from the JSP before making the call.

A similar concept is recommended to mitigate CSRF .

0
source

Just a little semantics. Requests are usually created from the browser that your JSP displays. You cannot stop another program from requesting your JSP and use any information you give them to request it again.

You can stop another web page viewed in the user's browser from querying your site. This is called fake site sub-fake . You can mitigate this scenario.

Thus, depending on what you are trying to prevent, CSRF solutions may work for you. You can find a ready-made solution from your web server. For example, here is Tomcat

0
source

Source: https://habr.com/ru/post/1389132/


All Articles