| 1 |
.. currentmodule:: flask_wtf.csrf |
| 2 |
|
| 3 |
.. _csrf: |
| 4 |
|
| 5 |
CSRF Protection |
| 6 |
=============== |
| 7 |
|
| 8 |
Any view using :class:`~flask_wtf.FlaskForm` to process the request is already |
| 9 |
getting CSRF protection. If you have views that don't use ``FlaskForm`` or make |
| 10 |
AJAX requests, use the provided CSRF extension to protect those requests as |
| 11 |
well. |
| 12 |
|
| 13 |
Setup |
| 14 |
----- |
| 15 |
|
| 16 |
To enable CSRF protection globally for a Flask app, register the |
| 17 |
:class:`CSRFProtect` extension. :: |
| 18 |
|
| 19 |
from flask_wtf.csrf import CSRFProtect |
| 20 |
|
| 21 |
csrf = CSRFProtect(app) |
| 22 |
|
| 23 |
Like other Flask extensions, you can apply it lazily:: |
| 24 |
|
| 25 |
csrf = CSRFProtect() |
| 26 |
|
| 27 |
def create_app(): |
| 28 |
app = Flask(__name__) |
| 29 |
csrf.init_app(app) |
| 30 |
|
| 31 |
.. note:: |
| 32 |
|
| 33 |
CSRF protection requires a secret key to securely sign the token. By default |
| 34 |
this will use the Flask app's ``SECRET_KEY``. If you'd like to use a |
| 35 |
separate token you can set ``WTF_CSRF_SECRET_KEY``. |
| 36 |
|
| 37 |
.. warning:: |
| 38 |
|
| 39 |
Make sure your webserver cache policy wont't interfere with the CSRF protection. |
| 40 |
If pages are cached longer than the ``WTF_CSRF_TIME_LIMIT`` value, then user browsers |
| 41 |
may serve cached page including expired CSRF token, resulting in random *Invalid* |
| 42 |
or *Expired* CSRF errors. |
| 43 |
|
| 44 |
HTML Forms |
| 45 |
---------- |
| 46 |
|
| 47 |
When using a ``FlaskForm``, render the form's CSRF field like normal. |
| 48 |
|
| 49 |
.. sourcecode:: html+jinja |
| 50 |
|
| 51 |
<form method="post"> |
| 52 |
{{ form.csrf_token }} |
| 53 |
</form> |
| 54 |
|
| 55 |
If the template doesn't use a ``FlaskForm``, render a hidden input with the |
| 56 |
token in the form. |
| 57 |
|
| 58 |
.. sourcecode:: html+jinja |
| 59 |
|
| 60 |
<form method="post"> |
| 61 |
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/> |
| 62 |
</form> |
| 63 |
|
| 64 |
The ``name`` attribute must match the ``WTF_CSRF_FIELD_NAME`` setting |
| 65 |
(``'csrf_token'`` by default). Otherwise the request fails with a |
| 66 |
``Bad Request: CSRF token missing`` error. Change the setting if you need a |
| 67 |
different field name. |
| 68 |
|
| 69 |
HTML Meta Tag |
| 70 |
------------- |
| 71 |
|
| 72 |
For JavaScript clients, the recommended way to expose the token to the page is |
| 73 |
to render it in a ``<meta>`` tag in the document ``<head>``. This is the |
| 74 |
convention used by Rails and recommended by the |
| 75 |
`OWASP CSRF prevention cheat sheet`_. |
| 76 |
|
| 77 |
.. sourcecode:: html+jinja |
| 78 |
|
| 79 |
<head> |
| 80 |
{{ csrf_meta_tag() }} |
| 81 |
</head> |
| 82 |
|
| 83 |
This renders ``<meta name="csrf-token" content="...">``. The attribute name is |
| 84 |
configurable via the ``WTF_CSRF_META_NAME`` setting, or per-call with the |
| 85 |
``name`` argument: ``{{ csrf_meta_tag(name="authenticity-token") }}``. |
| 86 |
|
| 87 |
.. _OWASP CSRF prevention cheat sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#storing-the-csrf-token-value-in-the-dom |
| 88 |
|
| 89 |
JavaScript Requests |
| 90 |
------------------- |
| 91 |
|
| 92 |
When sending an AJAX request, read the token from the meta tag and send it in |
| 93 |
the ``X-CSRFToken`` header. This pattern is compatible with a strict |
| 94 |
``Content-Security-Policy`` since no inline script is required. |
| 95 |
|
| 96 |
Using ``fetch``: |
| 97 |
|
| 98 |
.. sourcecode:: javascript |
| 99 |
|
| 100 |
const token = document.querySelector('meta[name="csrf-token"]').content; |
| 101 |
|
| 102 |
fetch("/api/resource", { |
| 103 |
method: "POST", |
| 104 |
headers: { "X-CSRFToken": token, "Content-Type": "application/json" }, |
| 105 |
body: JSON.stringify(data), |
| 106 |
}); |
| 107 |
|
| 108 |
Using Axios, configure the default header once at startup: |
| 109 |
|
| 110 |
.. sourcecode:: javascript |
| 111 |
|
| 112 |
axios.defaults.headers.common["X-CSRFToken"] = |
| 113 |
document.querySelector('meta[name="csrf-token"]').content; |
| 114 |
|
| 115 |
Customize the error response |
| 116 |
---------------------------- |
| 117 |
|
| 118 |
When CSRF validation fails, it will raise a :class:`CSRFError`. |
| 119 |
By default this returns a response with the failure reason and a 400 code. |
| 120 |
You can customize the error response using Flask's |
| 121 |
:meth:`~flask.Flask.errorhandler`. :: |
| 122 |
|
| 123 |
from flask_wtf.csrf import CSRFError |
| 124 |
|
| 125 |
@app.errorhandler(CSRFError) |
| 126 |
def handle_csrf_error(e): |
| 127 |
return render_template('csrf_error.html', reason=e.description), 400 |
| 128 |
|
| 129 |
Exclude views from protection |
| 130 |
----------------------------- |
| 131 |
|
| 132 |
We strongly suggest that you protect all your views with CSRF. But if |
| 133 |
needed, you can exclude some views using a decorator. :: |
| 134 |
|
| 135 |
@app.route('/foo', methods=('GET', 'POST')) |
| 136 |
@csrf.exempt |
| 137 |
def my_handler(): |
| 138 |
# ... |
| 139 |
return 'ok' |
| 140 |
|
| 141 |
You can exclude all the views of a blueprint. :: |
| 142 |
|
| 143 |
csrf.exempt(account_blueprint) |
| 144 |
|
| 145 |
You can disable CSRF protection in all views by default, by setting |
| 146 |
``WTF_CSRF_CHECK_DEFAULT`` to ``False``, and selectively call |
| 147 |
:meth:`~flask_wtf.csrf.CSRFProtect.protect` only when you need. This also enables you to do some |
| 148 |
pre-processing on the requests before checking for the CSRF token. :: |
| 149 |
|
| 150 |
@app.before_request |
| 151 |
def check_csrf(): |
| 152 |
if not is_oauth(request): |
| 153 |
csrf.protect() |
| 154 |
|
| 155 |
Pass ``apply_exemptions=True`` to keep ``@csrf.exempt`` working in this mode. |
| 156 |
The call will skip validation for views and blueprints marked as exempt. :: |
| 157 |
|
| 158 |
@app.before_request |
| 159 |
def check_csrf(): |
| 160 |
if not is_oauth(request): |
| 161 |
csrf.protect(apply_exemptions=True) |