How to prevent my servlet from being called from s

2019-06-22 17:15发布

问题:

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.

回答1:

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.



回答2:

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
}


回答3:

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