15

As can be seen in the following code, I have a GET for registration, that delegates its work to POST.

class RegistrationHandler(tornado.web.RequestHandler):
    def get(self):
        s = """
          <h1>Register</h1>
              <form method="post" action="/register">
                  <div>
                      <label>User</label>
                      <input name="user_name" value="[email protected]"/>
                  </div>
                  <div>
                      <label>password</label>
                      <input name="password" type="password"/>
                  </div>
                  <div>
                      <input type="submit" value="submit"/>
                  </div>
              </form>
        """
        self.write(s)

    @log_exception()
    def post(self):
        user_name = self.request.arguments['user_name']
        password = self.request.arguments['password']
        log.debug('Registering user with credentials %r' % (user_name, password))
        with sa_session() as db_session:
            User.register(user_name, password, db_session)

When I access the URL from my web browser, I get a registration form, after submitting which I get "403: Forbidden".

Console log:

2012-10-15 11:27:42,482 - __main__ - DEBUG - Starting server on port 8080
2012-10-15 11:27:49,377 - root - INFO - 304 GET /register (127.0.0.1) 0.78ms
2012-10-15 11:27:53,143 - root - WARNING - 403 POST /register (127.0.0.1): '_xsrf' argument missing from POST
2012-10-15 11:27:53,144 - root - WARNING - 403 POST /register (127.0.0.1) 1.05ms

What does this error mean and how do I correct it? Thanks.

4 Answers 4

21

I imagine you have Cross-site request forgery cookies enabled in your settings (by default it is on).

Tornado's XSRF is here

To fix this turn it off in your settings:

settings = {
    "xsrf_cookies": False,
}

Note: Normally you dont want to turn this off and normally you'd be generating HTML in a template like this: Please note the xsrf bit which adds the XSRF cookie.

 <form method="post" action="/register">
     <input name="user_name" value="[email protected]"/>
     <input name="password" type="password"/>
     <input type="submit" value="submit"/>
{% raw xsrf_form_html() %}
 </form>

---EDIT following comments--- Instead of:

  def get(self):
        loader = template.Loader("resources")
        page_contents = loader.load('register_page.html').generate()
        self.write(page_contents)

Do:

  def get(self):
     self.render("../resources/register_page.html")

or better:

  def get(self):
     self.render("register_page.html")

(and put it in your templates directory)

4
  • It raises an error that name xsrf_form_html() is not defined. Do I need some import? If yes, how do I add it in my template? Commented Oct 18, 2012 at 7:59
  • You dont need any special imports. Note that xsrf_form_html() will only work in a Template. The code you posted above is not a template.
    – andy boot
    Commented Oct 18, 2012 at 11:18
  • Here's my Python code - refheap.com/paste/5955, and here's my template - refheap.com/paste/5956. Commented Oct 18, 2012 at 11:40
  • The error message reads NameError: global name 'xsrf_form_html' is not defined. Commented Oct 18, 2012 at 11:43
2

Same issue here. After digging a while into the code I checked the tornado built-in function which makes that check:

def check_xsrf_cookie(self):
    """Verifies that the ``_xsrf`` cookie matches the ``_xsrf`` argument.

    To prevent cross-site request forgery, we set an ``_xsrf``
    cookie and include the same value as a non-cookie
    field with all ``POST`` requests. If the two do not match, we
    reject the form submission as a potential forgery.

    The ``_xsrf`` value may be set as either a form field named ``_xsrf``
    or in a custom HTTP header named ``X-XSRFToken`` or ``X-CSRFToken``
    (the latter is accepted for compatibility with Django).

    See http://en.wikipedia.org/wiki/Cross-site_request_forgery

    Prior to release 1.1.1, this check was ignored if the HTTP header
    ``X-Requested-With: XMLHTTPRequest`` was present.  This exception
    has been shown to be insecure and has been removed.  For more
    information please see
    http://www.djangoproject.com/weblog/2011/feb/08/security/
    http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails

    .. versionchanged:: 3.2.2
       Added support for cookie version 2.  Both versions 1 and 2 are
       supported.
    """
    token = (self.get_argument("_xsrf", None) or
             self.request.headers.get("X-Xsrftoken") or
             self.request.headers.get("X-Csrftoken"))
    if not token:
        raise HTTPError(403, "'_xsrf' argument missing from POST")
    _, token, _ = self._decode_xsrf_token(token)
    _, expected_token, _ = self._get_raw_xsrf_token()
    if not token:
        raise HTTPError(403, "'_xsrf' argument has invalid format")
    if not _time_independent_equals(utf8(token), utf8(expected_token)):
        raise HTTPError(403, "XSRF cookie does not match POST argument")

As you can read into the method definition:

The _xsrf value may be set as either a form field named _xsrf or in a custom HTTP header named X-XSRFToken or X-CSRFToken

Therefore I tried setting an HTTP header named X-CSRFToken. The following is the ajax definition:

$.ajax({
    url: this.my_url,
    type: 'POST',
    data: JSON.stringify(body),
    beforeSend: function(xhr) {
            xhr.setRequestHeader('X-CSRFToken', getCookie('_xsrf'));},
});

Lastly, we need to define the function getCookie which is responsible for retrieving the right CSRF-token. The definition of this function has been taken directly from the Tornado CSRF documentation:

function getCookie(name) {
    var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
    return r ? r[1] : undefined;
}
0

there is a conflict : how do you make get and in the form you put method="post" ? this why there is error 403

if you use get, then you will not need an xsrf protection. else, you add it after the form declaration as

<form method="post" action="/register">
{% raw xsrf_form_html() %} # the 'raw' word is to force escape to be desactivated (it is by default activated)

so the xsrf you'll find it a hidden tag in your rendered html.

0

I solved it changing the form method in the HTML file: <form method="post" action="/register"> for <form method="POST" action="/register

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.