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.
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.
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
}
Simply you can prevent by the following.
- Use
POST
method since more difficult to hack ; Diff GET vs POST
- Ignore GET method which can be sent directly if type URL in browser
- Check with authentication username,password before process the request
- Consider writing an authorization
Filter