Shankar
Shankar

Reputation: 117

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.

Upvotes: 5

Views: 1853

Answers (3)

vels4j
vels4j

Reputation: 11298

Simply you can prevent by the following.

  1. Use POST method since more difficult to hack ; Diff GET vs POST
  2. Ignore GET method which can be sent directly if type URL in browser
  3. Check with authentication username,password before process the request
  4. Consider writing an authorization Filter

Upvotes: 0

Luigi
Luigi

Reputation: 8847

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.

Upvotes: 6

Joop Eggen
Joop Eggen

Reputation: 109613

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
}

Upvotes: 1

Related Questions