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.
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)
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 namedX-XSRFToken
orX-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;
}
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