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.
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.
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.
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."
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With