Flask Snippets

This is an archived view of user-submitted snippets. Despite being
hosted on the Flask site, they are not official. No Flask
maintainer has curated or checked the snippets for security,
correctness, or design.

This snippet by Dan Jacob can be used freely for
anything you like. Consider it public domain.

Comments

abort instead of exception
by Armin Ronacher
on 2010-05-03 @ 11:42

I would recommend using abort(400) instead of raise Forbidden. First of all it's part of the Flask API (the abort) function and it also matches HTTP better here. It is a bad request and not really a forbidden URL.

403 used in Django
by Dan Jacob
on 2010-05-03 @ 11:55

Sure - the main reason I used 403 was because (rightly or wrongly) that's what Django uses:

One last thing I saw missing while trying to get this up myself is the hidden input field is missing the name attribute. It should be

<inputtype=hiddenname=_csrf_tokenvalue="{{csrf_token()}}">

PS - its working wonderfully now

Last line typo
by justquick
on 2010-05-04 @ 04:38

The last line should read

app.jinja_env.globals['csrf_token']=generate_csrf_token

I also think that abort(403) is the best way to handle this

Last line update
by Max Countryman
on 2011-02-23 @ 22:51

I believe

`app.jinja_env.globals['csrf_token'] = generate_csrf_token`

should be

`app.jinja_env.filters['csrf_token'] = generate_csrf_token`

Please disregard
by Max Countryman
on 2011-02-24 @ 00:00

I'm sorry, I was wrong about the above post. Please disregard/remove.

What about JSON API?
by Shuhao
on 2012-06-21 @ 00:44

How would you protect yourself against CSRF if you have JSON apis?

re: What about JSON API?
by Nick
on 2012-08-22 @ 10:37

Just define a GET method which returns the CSRF token.

how to handle session timeouts
by Andrew Kloos
on 2012-10-29 @ 18:20

Let's say someone navigates to your page which contains a form with your csrf token. Now let's says they wait on the page and their session timeout out. How do you handle them posting while their session has already timed out? Thanks!

Testing
by Geri
on 2015-03-11 @ 12:43

In order to disable the CSRF functionality for testing purposes you can set the config entry WTF_CSRF_ENABLED to False.