Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent my servlet from being called from some other website

Okay so I have a simple servlet like this.

public class SimpleServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/plain");
    resp.getWriter().println(req.getParameter("name"));

    }
}

Lets say it gets triggered when I use this URL /simple_servlet.do

How do I ensure that this servlet works only if it is called from my website and not from some other website. In other words is there some request parameter (which cannot be spoofed) that lets me know.

like image 704
Shankar Avatar asked Jan 04 '13 06:01

Shankar


People also ask

How do you stop a servlet?

There certainly is - just have your doPost method throw an UnavailableException (in the javax. servlet package) You can either make it permanently stopped or unavailable for NN seconds. Subsequent requests to the servlet will get an unavailable message.

Which protocol is used to interact with web client by servlet?

Java servlets typically run on the HTTP protocol. HTTP is an asymmetrical request-response protocol. The client sends a request message to the server, and the server returns a response message as illustrated.

What is HttpServletRequest and HttpServletResponse?

HttpServletRequest "extends the ServletRequest interface to provide request information for HTTP servlets." HttpServletResponse "extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies."

What is cookie in servlet?

A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.


2 Answers

The only way I can think of, is that you to generate a Token on the server from your website (for example an MD5 on the JSESSIONID), and pass that token back to your servlet. Only your website knows the token, other website cannot steal cookies (including the JSESSIONID) and compute the token from outside. This should be safe also from XSRF attacks.

like image 172
Luigi R. Viggiano Avatar answered Oct 07 '22 05:10

Luigi R. Viggiano


You can use the session between client and server to detect whether the first time.

if (req.getSession(false) == null) { // false = do not create a session
   // No user session
}
like image 27
Joop Eggen Avatar answered Oct 07 '22 03:10

Joop Eggen