| 1 |
Security Patterns |
| 2 |
================= |
| 3 |
|
| 4 |
.. danger:: |
| 5 |
Be aware that starting in Flask 2.2.0, they recommend extensions store context information |
| 6 |
on ``g`` which is the application context. Prior to this many extensions (including |
| 7 |
Flask-Security and Flask-Login) stored things like user credential information on the |
| 8 |
request context. These are now stored on ``g`` i.e. the application context. It is imperative |
| 9 |
that applications not mistakenly push their own application context and forget to pop it - in that |
| 10 |
case Flask won't push a new application context nor will it pop it at the end of the request - thus |
| 11 |
credential information could leak from one user request to another. |
| 12 |
|
| 13 |
Authentication and Authorization |
| 14 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 15 |
Flask-Security provides a set of authentication decorators: |
| 16 |
|
| 17 |
* :func:`.auth_required` |
| 18 |
|
| 19 |
* :func:`.http_auth_required` |
| 20 |
|
| 21 |
* :func:`.auth_token_required` |
| 22 |
|
| 23 |
and a set of authorization decorators: |
| 24 |
|
| 25 |
* :func:`.roles_required` |
| 26 |
|
| 27 |
* :func:`.roles_accepted` |
| 28 |
|
| 29 |
* :func:`.permissions_required` |
| 30 |
|
| 31 |
* :func:`.permissions_accepted` |
| 32 |
|
| 33 |
In addition, Flask-Login provides @login_required. In order to take advantage of all the |
| 34 |
Flask-Security features, it is recommended to NOT use @login_required. |
| 35 |
|
| 36 |
Also, if you annotate your endpoints with JUST an authorization decorator, you will never |
| 37 |
get a 401 response, and (for forms) you won't be redirected to your login page. In this case |
| 38 |
you will always get a 403 status code (assuming you don't override the default handlers). |
| 39 |
|
| 40 |
While these annotations are quick and easy, it is likely that they won't completely satisfy |
| 41 |
all an application's authorization requirements. A common example might be that a user can |
| 42 |
only edit their own posts/documents. In cases like this - it is nice to have a uniform way |
| 43 |
of handling all authorization errors. A simple way to do this is to use a special exception |
| 44 |
class that you can raise either in response to Flask-Security authorization failures, or in your |
| 45 |
own code. Then use Flask's ``errorhandler`` to catch that exception and create the appropriate API response:: |
| 46 |
|
| 47 |
class MyForbiddenException(Exception): |
| 48 |
def __init__(self, msg='Not permitted with your privileges', status=http.HTTPStatus.FORBIDDEN): |
| 49 |
self.info = {'status': status, 'msgs': [msg]} |
| 50 |
|
| 51 |
_security = app.extensions["security"] |
| 52 |
|
| 53 |
@_security.unauthz_handler |
| 54 |
def my_unauthz_handler(func, params): |
| 55 |
raise MyForbiddenException() |
| 56 |
|
| 57 |
@app.errorhandler(MyForbiddenException) |
| 58 |
def my_exception(ex): |
| 59 |
return flask.jsonify(ex.info), ex.info['status'] |
| 60 |
|
| 61 |
@app.route('/doc/<int:doc_id>', methods=['PATCH']) |
| 62 |
@auth_required('token', 'session') |
| 63 |
def doc_patch(doc_id): |
| 64 |
doc = fetch_doc(doc_id) |
| 65 |
if not current_user.has_role('admin') and doc.owner != current_user: |
| 66 |
raise MyForbiddenException(msg='You can only update docs you own') |
| 67 |
|
| 68 |
|
| 69 |
A note about Basic Auth |
| 70 |
+++++++++++++++++++++++ |
| 71 |
Basic Auth is supported in Flask-Security, using the @http_auth_required() decorator. If a request for an endpoint |
| 72 |
protected with @http_auth_required is received, and the request doesn't contain the appropriate HTTP Headers, a 401 is returned |
| 73 |
along with the required WWW-Authenticate header. In this case there won't be a usable session cookie returned so all future requests |
| 74 |
will also require credentials to be sent. Effectively the caller is temporarily 'logged in' at the beginning of each request and 'logged out' again |
| 75 |
at the end of the request. Most (all?) browsers intercept this response and pop up a login dialog box and remember, for the site, the entered credentials. |
| 76 |
This effectively bypasses any of the normal Flask-Security login forms. By default, the Flask-Security endpoints that require the caller be |
| 77 |
authenticated do NOT support ``basic`` - however the :py:data:`SECURITY_API_ENABLED_METHODS` can be used to override this. |
| 78 |
|
| 79 |
.. _token_topic: |
| 80 |
|
| 81 |
Authentication and Refresh Tokens |
| 82 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 83 |
Simple authentication tokens are supported out of the box. Their expiration/lifetime |
| 84 |
can be set both globally or per-user (see below). In addition, the optional :py:data:`SECURITY_REFRESH_TOKEN` |
| 85 |
feature provides a robust refresh token implementation. |
| 86 |
|
| 87 |
Authentication tokens are generated using a uniquifier field in the |
| 88 |
user's UserModel. By default that field is ``fs_uniquifier``. This means that |
| 89 |
if that field is changed (via :meth:`.UserDatastore.set_uniquifier`) |
| 90 |
then any existing authentication tokens will no longer be valid. This value is changed |
| 91 |
whenever a user changes their password. If this is not the desired behavior then you can add an additional |
| 92 |
field to the UserModel: ``fs_token_uniquifier`` and that will be used instead, thus |
| 93 |
isolating password changes from authentication tokens. That field can be changed via |
| 94 |
:meth:`.UserDatastore.set_token_uniquifier`. This field should have ``unique=True``. |
| 95 |
Unlike ``fs_uniquifier``, it can be set to ``nullable`` - it will automatically be generated |
| 96 |
at first use if None. |
| 97 |
|
| 98 |
Authentication tokens have 2 options for specifying expiry time: :data:`SECURITY_TOKEN_MAX_AGE` |
| 99 |
is applied to ALL authentication tokens. Each authentication token can itself have an embedded |
| 100 |
expiry value (settable via the :data:`SECURITY_TOKEN_EXPIRE_TIMESTAMP` callable). |
| 101 |
|
| 102 |
Authentication tokens also convey freshness by recording the time the token was generated. |
| 103 |
This is used for endpoints protected with :func:`.auth_required` with a ``within`` |
| 104 |
value set. |
| 105 |
|
| 106 |
The refresh token feature consists of: |
| 107 |
|
| 108 |
- a DB model - :ref:`FsRefreshTracker <refresh_tracker_model>` to keep track of each refresh token family |
| 109 |
- a view :py:data:`SECURITY_REFRESH_TOKEN_URL` that issues a new authentication |
| 110 |
token given a valid refresh token |
| 111 |
- refresh token rotation |
| 112 |
- built-in re-use protection |
| 113 |
- return refresh token as a cookie (default) OR in the JSON response |
| 114 |
- revoke refresh token/tracker on logout |
| 115 |
|
| 116 |
The refresh token (when enabled) is returned along with the authentication token from any |
| 117 |
authentication endpoint. By default, it is returned as a cookie (http-only). |
| 118 |
Each new refresh token is tracked in the DB with a FsRefreshTracker entry. |
| 119 |
Each time a new authentication_token is requested (via the .refresh_token endpoint) the generation |
| 120 |
number of the refresh tracker entry is incremented, and a new refresh token is generated and returned. |
| 121 |
This effectively makes refresh tokens single use. |
| 122 |
|
| 123 |
The ``.logout`` endpoint takes a ``refresh_token`` as an optional item - if supplied - that refresh token |
| 124 |
and the associated tracker will be revoked - this should be the best practice for any application. If the |
| 125 |
refresh token is being managed via a cookie, the cookie will be deleted. |
| 126 |
|
| 127 |
.. _freshness_topic: |
| 128 |
|
| 129 |
Freshness |
| 130 |
~~~~~~~~~ |
| 131 |
A common pattern for browser-based sites is to use sessions to manage identity. This is usually |
| 132 |
implemented using session cookies. These cookies expire once the session (browser tab) is closed. This is very |
| 133 |
convenient, and keeps the users from having to constantly reauthenticate. The downside is that sessions can easily be |
| 134 |
open for days or weeks. This adds to the security risk that some bad-actor or XSS gets control of the browser and then can |
| 135 |
do anything the user can. To mitigate that, operations that change fundamental identity characteristics (such as email, password, etc.) |
| 136 |
can be protected by requiring a 'fresh' or recent authentication. Flask-Security supports this with the following: |
| 137 |
|
| 138 |
- :func:`.auth_required` takes parameters that define how recent the authentication must have happened. In addition a grace |
| 139 |
period can be specified so that multiple step operations don't require reauthentication in the middle. |
| 140 |
- A default :meth:`.Security.reauthn_handler` that is called when a request fails the recent authentication check. |
| 141 |
- :py:data:`SECURITY_VERIFY_URL`, :py:data:`SECURITY_US_VERIFY_URL`, :py:data:`SECURITY_WAN_VERIFY_URL`, |
| 142 |
:py:data:`SECURITY_OAUTH_VERIFY_START_URL` endpoints |
| 143 |
that request the user to reauthenticate. |
| 144 |
- ``VerifyForm``, ``UsVerifyForm``, ``WebAuthnVerifyForm`` forms that can be extended. |
| 145 |
|
| 146 |
Flask-Security itself uses this as part of securing the following endpoints: |
| 147 |
|
| 148 |
- .wan_register ("/wan-register") |
| 149 |
- .wan_delete ("/wan-delete") |
| 150 |
- .tf_setup ("/tf-setup") |
| 151 |
- .us_setup ("/us-setup") |
| 152 |
- .mf_recovery_codes ("/mf-recovery-codes") |
| 153 |
- .change_email ("/change-email") |
| 154 |
- .change_username ("/change-username") |
| 155 |
- .change_password ("/change") |
| 156 |
|
| 157 |
using the :py:data:`SECURITY_FRESHNESS` and :py:data:`SECURITY_FRESHNESS_GRACE_PERIOD` configuration variables. |
| 158 |
|
| 159 |
.. tip:: |
| 160 |
The timestamp of the users last successful authentication is stored in the session |
| 161 |
as well as in the authentication token. One of these must be presented or freshness |
| 162 |
will fail. You can disallow using the value in the authentication token by setting |
| 163 |
:py:data:`SECURITY_FRESHNESS_ALLOW_AUTH_TOKEN` to ``False``. |
| 164 |
You can disable freshness by setting ``SECURITY_FRESHNESS`` to ``timedelta(minutes=-1)`` |
| 165 |
|
| 166 |
.. _redirect_topic: |
| 167 |
|
| 168 |
Open Redirect Exposure |
| 169 |
~~~~~~~~~~~~~~~~~~~~~~~ |
| 170 |
Flask-Security, accepts a ``next=xx`` parameter (either |
| 171 |
as a query param OR in the POSTed form) which it will use when completing an operation |
| 172 |
which results in a redirection. If a malicious user/ |
| 173 |
application can inject an arbitrary ``next`` parameter which redirects to an external |
| 174 |
location, this results in a security vulnerability called an `open redirect`. |
| 175 |
The following endpoints accept a ``next`` parameter: |
| 176 |
|
| 177 |
- .login ("/login") |
| 178 |
- .logout ("/logout") |
| 179 |
- .register ("/register") |
| 180 |
- .verify ("/verify") |
| 181 |
- .two_factor_token_validation ("/tf-validate") |
| 182 |
- .wan_verify_response ("/wan-verify") |
| 183 |
- .wan_signin_response ("/wan-signin") |
| 184 |
- .us_signin ("/us-signin") |
| 185 |
- .us_verify ("/us-verify") |
| 186 |
- .oauthstart ("/oauthstart") |
| 187 |
- .oauth_verify_start ("/oauth-verify-start") |
| 188 |
|
| 189 |
Flask-Security always quotes the path portion of a user supplied URL. |
| 190 |
This `link <https://www.cve.org/CVERecord?id=CVE-2021-32618>`_ provides background of why simple parsing of URLs isn't enough. |
| 191 |
|
| 192 |
|
| 193 |
.. _pass_validation_topic: |
| 194 |
|
| 195 |
Password Validation and Complexity |
| 196 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 197 |
There is a large body of references (and endless discussions) around how to get users to create |
| 198 |
good passwords. The `OWASP Authentication cheatsheet <https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html>`_ |
| 199 |
is a useful place to start. Flask-Security has a default password validator that: |
| 200 |
|
| 201 |
* Checks for minimum and maximum length (minimum is configurable via :py:data:`SECURITY_PASSWORD_LENGTH_MIN`). |
| 202 |
The default is 8 characters as defined by `NIST <https://pages.nist.gov/800-63-3/sp800-63b.html>`_. |
| 203 |
* If :py:data:`SECURITY_PASSWORD_CHECK_BREACHED` is set, will use the API for `haveibeenpwned <https://haveibeenpwned.com>`_ to |
| 204 |
check if the password is on a list of breached passwords. The configuration variable :py:data:`SECURITY_PASSWORD_BREACHED_COUNT` |
| 205 |
can be used to set the minimum allowable 'breaches'. |
| 206 |
* If :py:data:`SECURITY_PASSWORD_COMPLEXITY_CHECKER` is set to ``zxcvbn`` and the |
| 207 |
package `zxcvbn <https://pypi.org/project/zxcvbn/>`_ is installed, it will check the password for complexity. |
| 208 |
|
| 209 |
Be aware that ``zxcvbn`` is not actively being maintained, and has localization issues. |
| 210 |
|
| 211 |
In addition to validation, unicode passwords should be normalized as specified |
| 212 |
by NIST requirement: `5.1.1.2 Memorized Secret Verifiers`_. Normalization can |
| 213 |
be disabled by setting the :py:data:`SECURITY_PASSWORD_NORMALIZE_FORM` to ``None``. |
| 214 |
Validation and normalization is encapsulated in :class:`.PasswordUtil`. |
| 215 |
This can be overridden by passing your class at app initialization time. |
| 216 |
The :meth:`.PasswordUtil.validate` is passed additional kwargs to allow custom |
| 217 |
validators more flexibility. |
| 218 |
A custom validator can still call the underlying methods where appropriate: |
| 219 |
:func:`flask_security.password_length_validator`, :func:`flask_security.password_complexity_validator`, |
| 220 |
and :func:`flask_security.password_breached_validator`. |
| 221 |
|
| 222 |
.. _5.1.1.2 Memorized Secret Verifiers: https://pages.nist.gov/800-63-3/sp800-63b.html#sec5 |
| 223 |
|
| 224 |
|
| 225 |
.. _generic_responses: |
| 226 |
|
| 227 |
Generic Responses - Avoiding User Enumeration |
| 228 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 229 |
How an application responds to API requests that contain identity or authentication information |
| 230 |
can give would-be attackers insight into active users on the system. OWASP has a great `cheat-sheet`_ describing |
| 231 |
this and useful ways to avoid it. Flask-Security supports this by setting the |
| 232 |
:py:data:`SECURITY_RETURN_GENERIC_RESPONSES` configuration to ``True``. As documented in the cheat-sheet - this does |
| 233 |
come with some usability concerns. The following endpoints are affected: |
| 234 |
|
| 235 |
* :py:data:`SECURITY_REGISTER_URL` - The same response will be returned whether the email (or username) is already in the |
| 236 |
system or not. JSON requests will ALWAYS return 200. If :py:data:`SECURITY_CONFIRMABLE` is set (it should be!), the |
| 237 |
`SECURITY_MSG_CONFIRM_REGISTRATION` message will be flashed for both new and existing email addresses. Detailed errors will still |
| 238 |
be returned for things like insufficient password complexity, etc.. In the case of trying to register an existing email, an email will be sent to that email address |
| 239 |
explaining that they are already registered and displaying the associated username (if any) and provide a hint on how to reset their |
| 240 |
password if they forgot it. In the case of a new email but an already registered username, an email will be sent saying that the |
| 241 |
user must try registering again with a different username. |
| 242 |
* :py:data:`SECURITY_LOGIN_URL` - For any errors (unknown username, inactive account, bad password) the `SECURITY_MSG_GENERIC_AUTHN_FAILED` |
| 243 |
message will be returned. |
| 244 |
* :py:data:`SECURITY_RESET_URL` - In all cases the `SECURITY_MSG_PASSWORD_RESET_REQUEST` message will be flashed. For JSON |
| 245 |
a 200 will always be returned (whether an email was sent or not). |
| 246 |
``Note``: If the application overrides the form and adds an additional field (e.g. `captcha`) and that field has |
| 247 |
a validation error, a normal form error response will be returned (and JSON will return a 400). |
| 248 |
* :py:data:`SECURITY_CONFIRM_URL` - In all cases the `SECURITY_MSG_CONFIRMATION_REQUEST` message will be flashed. For JSON |
| 249 |
a 200 will always be returned (whether an email was sent or not). |
| 250 |
``Note``: If the application overrides the form and adds an additional field (e.g. `captcha`) and that field has |
| 251 |
a validation error, a normal form error response will be returned (and JSON will return a 400). |
| 252 |
* :py:data:`SECURITY_US_SIGNIN_SEND_CODE_URL` - The `SECURITY_MSG_GENERIC_US_SIGNIN` message will be flashed in all cases - |
| 253 |
whether a selected method is setup for the user or not. |
| 254 |
* :py:data:`SECURITY_US_SIGNIN_URL` - For any errors (unknown username, inactive account, bad passcode) the `SECURITY_MSG_GENERIC_AUTHN_FAILED` |
| 255 |
message will be returned. |
| 256 |
* :py:data:`SECURITY_US_VERIFY_LINK_URL` - For any errors (unknown username, inactive account, bad passcode) the `SECURITY_MSG_GENERIC_AUTHN_FAILED` |
| 257 |
message will be returned. |
| 258 |
|
| 259 |
|
| 260 |
In the case of an application using a ``username`` as an identity it should be noted that it is possible for a bad-actor to enumerate usernames, albeit slowly, |
| 261 |
by parsing emails. |
| 262 |
|
| 263 |
Note also that :py:data:`SECURITY_REQUIRES_CONFIRMATION_ERROR_VIEW` is ignored in these cases. If your application is using WebAuthn, be sure |
| 264 |
to set :py:data:`SECURITY_WAN_ALLOW_USER_HINTS` to ``False``. |
| 265 |
|
| 266 |
|
| 267 |
.. _cheat-sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html#authentication-and-error-messages |
| 268 |
|
| 269 |
.. _csrf_topic: |
| 270 |
|
| 271 |
CSRF |
| 272 |
~~~~ |
| 273 |
By default, Flask-Security, via Flask-WTForms protects all form based POSTS |
| 274 |
from CSRF attacks using well vetted per-session hidden-form-field csrf-tokens. |
| 275 |
|
| 276 |
Any web application that uses a session cookie for authentication must have CSRF protection. |
| 277 |
For more details please read this `OWASP CSRF cheatsheet <https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md>`_. |
| 278 |
As mentioned in the OWASP cheatsheet - pure JSON requests should be immune from CSRF exploits ASSUMING that the application |
| 279 |
has a properly set CORS policy. Flask-Security, via Werkzeug, is careful to ONLY accept JSON with an ``"application/+json"`` header. |
| 280 |
However, currently, there is no way to configure Flask-Security to accept ONLY ``"application/json"`` - meaning that it is important |
| 281 |
to properly pass CSRF tokens for ALL requests. |
| 282 |
|
| 283 |
Flask-Security strives to support various options for both its endpoints (e.g. ``/login``) |
| 284 |
and the application endpoints (protected with Flask-Security decorators such as :func:`.auth_required`). |
| 285 |
|
| 286 |
If your application just uses forms that are derived from ``Flask-WTF::Flaskform`` - you are done. |
| 287 |
All of Flask-Security's endpoints are form based (regardless of how the request was made). |
| 288 |
|
| 289 |
Login CSRF |
| 290 |
++++++++++++ |
| 291 |
Read more about this at `OWASP <https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.md#possible-csrf-vulnerabilities-in-login-forms>`_. |
| 292 |
|
| 293 |
Logout CSRF |
| 294 |
++++++++++++ |
| 295 |
Prior to release 5.9 the logout endpoint never accepted any input nor enabled CSRF protection so |
| 296 |
there was never any possible errors. Furthermore, both ``"GET"`` and ``"POST"`` were accepted. |
| 297 |
Best practice is to accept only ``"POST"`` requests to avoid trivial 'auto-logout' attacks. |
| 298 |
Requiring CSRF for the logout endpoint is best practice - however there are many |
| 299 |
sources that disagree with this (and in fact, security advisories are usually NOT issued for applications that don't |
| 300 |
support that). The usability issue is that users may or may not be looking for an error when they click the logout button |
| 301 |
and NOT logging them out is worse. Flask-Security supports requiring CSRF for logout with the |
| 302 |
:py:data:`SECURITY_LOGOUT_CSRF` configuration option. |
| 303 |
|
| 304 |
.. warning:: |
| 305 |
Enabling CSRF protection means that the logout endpoint can return an error - be sure your application |
| 306 |
handles that. For form based applications, Flask-Security will return a 'Confirm Sign Out' template. |
| 307 |
|
| 308 |
Behind-The-Scenes |
| 309 |
++++++++++++++++++ |
| 310 |
Depending on configuration, there are 3 places CSRF tokens can be checked (in order): |
| 311 |
#) As part of an @before_request handler that Flask-WTF sets up if CSRFprotect(app) is called. On error |
| 312 |
this always returns HTTP 400 and small snippet of HTML. This can be disabled |
| 313 |
by setting app.config["WTF_CSRF_CHECK_DEFAULT"] = False. |
| 314 |
#) As part of a Flask-Security decorator (:func:`.unauth_csrf`, :func:`.auth_required`). On |
| 315 |
error, either a JSON response is returned OR CSRFError exception is raised and 400 is returned with the small snippet of HTML |
| 316 |
(the exception and default response is part of Flask-WTF). |
| 317 |
#) As part of form validation for any form derived from FlaskForm (which all Flask-Security |
| 318 |
forms are). An error here is recorded in the ``csrf_token`` field and the calling view |
| 319 |
decides whether to return 200 or 400. |
| 320 |
This is the default if no other configuration changes are made. |
| 321 |
|
| 322 |
CSRF: Single-Page-Applications and AJAX/XHR |
| 323 |
++++++++++++++++++++++++++++++++++++++++++++ |
| 324 |
If you are thinking about using authentication tokens in your browser-based UI - read |
| 325 |
`this article <https://stormpath.com/blog/where-to-store-your-jwts-cookies-vs-html5-web-storage>`_ |
| 326 |
on how and where to store authentication tokens. While the |
| 327 |
article is talking about JWT it applies to Flask-Security tokens as well. |
| 328 |
|
| 329 |
In general, it is considered more secure (and easier) to use sessions for browser |
| 330 |
based UI, and tokens for service to service and scripts. |
| 331 |
|
| 332 |
For SPA, and especially those that aren't served via your flask application, there are difficulties |
| 333 |
with actually retrieving and using a CSRF token. There are 2 normal ways to do this: |
| 334 |
|
| 335 |
* Have the csrf-token available via a JSON GET request that can be attached as a |
| 336 |
header in every mutating request. |
| 337 |
* Have a cookie that can be read via JavaScript whose value is the csrf-token that |
| 338 |
can be attached as a header in every mutating request. |
| 339 |
|
| 340 |
Flask-Security supports both solutions. |
| 341 |
|
| 342 |
Explicit fetch and send of csrf-token |
| 343 |
-------------------------------------- |
| 344 |
The current session CSRF token |
| 345 |
is returned on every JSON GET request (to a Flask-Security endpoint) as ``response['csrf_token`]``. |
| 346 |
For web applications that ARE served via flask, it is even easier to get the csrf-token - |
| 347 |
`<https://flask-wtf.readthedocs.io/en/1.2.x/csrf/>`_ gives some useful tips. |
| 348 |
|
| 349 |
Armed with the csrf-token, the UI must include that in every mutating operation. |
| 350 |
Be careful NOT to include the csrf-token in non-mutating requests (such as GETs). |
| 351 |
If your application uses GET to actually modify state - please stop. |
| 352 |
|
| 353 |
An example using `axios <https://github.com/axios/axios>`_ :: |
| 354 |
|
| 355 |
|
| 356 |
# This will fetch the csrf-token. Note that we do a GET on the login endpoint |
| 357 |
# which will get us the csrf-token even though we aren't yet logged in. |
| 358 |
# Note further the 'data: null' and explicit Content-Type header - these are |
| 359 |
# critical, otherwise Flask-Security will return the login form. |
| 360 |
axios.get('/login',{data: null, headers: {'Content-Type': 'application/json'}}).then(function (resp) { |
| 361 |
csrf_token = resp.data['response']['csrf_token'] |
| 362 |
}) |
| 363 |
|
| 364 |
|
| 365 |
# This will add the token header to each outgoing mutating request. |
| 366 |
axios.interceptors.request.use(function (config) { |
| 367 |
if (["post", "delete", "patch", "put"].includes(config["method"])) { |
| 368 |
if (csrf_token !== '') { |
| 369 |
config.headers["X-CSRF-Token"] = csrf_token |
| 370 |
} |
| 371 |
} |
| 372 |
return config; |
| 373 |
}, function (error) { |
| 374 |
// Do something with request error |
| 375 |
return Promise.reject(error); |
| 376 |
}); |
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
Note that we use the header name ``X-CSRF-Token`` as that is one of the default |
| 381 |
headers configured in Flask-WTF (*WTF_CSRF_HEADERS*) |
| 382 |
|
| 383 |
To protect your application's endpoints (that presumably are not using Flask forms), |
| 384 |
you need to enable CSRF as described in the FlaskWTF `documentation <https://flask-wtf.readthedocs.io/en/1.2.x/csrf/>`_: :: |
| 385 |
|
| 386 |
flask_wtf.CSRFProtect(app) |
| 387 |
|
| 388 |
This will turn on CSRF protection on ALL endpoints, including Flask-Security. This protection differs slightly from |
| 389 |
the default that is part of FlaskForm in that it will first look at the request body and see if it can find a form field that contains |
| 390 |
the csrf-token, and if it can't, it will check if the request has a header that is listed in *WTF_CSRF_HEADERS* and use that. |
| 391 |
Be aware that if you enable this it will ONLY work if you send the session cookie on each request. |
| 392 |
|
| 393 |
.. note:: |
| 394 |
It is IMPORTANT that you initialize/call ``CSRFProtect`` PRIOR to initializing Flask-Security. |
| 395 |
|
| 396 |
.. note:: |
| 397 |
Calling CSRFProtect(app) will setup a @before_request handler to verify CSRF - this occurs BEFORE any Flask-Security decorators |
| 398 |
or other view/form logic. One side effect is that CSRFProtect, on error, will raise a BadRequest error which returns a small |
| 399 |
piece of HTML by default - your application will need to add a Flask ErrorHandler to change that. Alternatively, and recommended |
| 400 |
is to set `WTF_CSRF_CHECK_DEFAULT` to `False` - which will disable the @before_request and let Flask-Security handle CSRF protection |
| 401 |
including properly returning a JSON response if the caller asks for it. |
| 402 |
|
| 403 |
.. danger:: |
| 404 |
If you set `WTF_CSRF_CHECK_DEFAULT` to `False` this will turn off CSRF checking for all your endpoints unless they are protected with |
| 405 |
@auth_required() or have explicit CSRF checking. |
| 406 |
|
| 407 |
|
| 408 |
Using a Cookie |
| 409 |
-------------- |
| 410 |
You can instruct Flask-Security to send a cookie that contains the csrf token. |
| 411 |
The cookie will be set on a call to ``GET /login`` or ``GET /us-signin`` - as well as after a successful authentication. |
| 412 |
This can be very convenient since various JavaScript AJAX packages are pre-configured to extract the contents of a cookie |
| 413 |
and send it on every mutating request as an HTTP header. `axios`_ for example has a default configuration |
| 414 |
that it will look for a cookie named ``XSRF-TOKEN`` and will send the contents of that back |
| 415 |
in an HTTP header called ``X-XSRF-Token``. This means that if you use that package you don't need to make |
| 416 |
any changes to your UI and just need the following configuration:: |
| 417 |
|
| 418 |
# Have cookie sent |
| 419 |
app.config["SECURITY_CSRF_COOKIE_NAME"] = "XSRF-TOKEN" |
| 420 |
|
| 421 |
# Don't have csrf tokens expire (they are invalid after logout) |
| 422 |
app.config["WTF_CSRF_TIME_LIMIT"] = None |
| 423 |
|
| 424 |
# Enable CSRF protection |
| 425 |
flask_wtf.CSRFProtect(app) |
| 426 |
|
| 427 |
Angular's `httpClient`_ also supports this. |
| 428 |
|
| 429 |
For React based projects you are free to choose your http client (`fetch` is bundled by default). Retrieving the token is easy:: |
| 430 |
|
| 431 |
fetch(url, { |
| 432 |
credentials: 'include', |
| 433 |
mode: 'cors', |
| 434 |
headers: { |
| 435 |
'Accept': 'application/json', |
| 436 |
'X-XSRF-TOKEN': getCookieValue('XSRF-TOKEN') |
| 437 |
} |
| 438 |
}); |
| 439 |
|
| 440 |
Sending the token on every mutating request is something that you should implement yourself. As an example an API call to an API |
| 441 |
endpoint that does CSRF validation:: |
| 442 |
|
| 443 |
function addUser(details) { |
| 444 |
return fetch('https://api.example.com/user', { |
| 445 |
mode: 'cors', |
| 446 |
method: 'POST', |
| 447 |
credentials: 'include', |
| 448 |
body: JSON.stringify(details), |
| 449 |
headers: { |
| 450 |
'Content-Type': 'application/json', |
| 451 |
'Accept': 'application/json', |
| 452 |
'X-XSRF-TOKEN': getCookieValue('XSRF-TOKEN') |
| 453 |
} |
| 454 |
}).then(response => { |
| 455 |
return response.json().then(data => { |
| 456 |
if (response.ok) { |
| 457 |
return data; |
| 458 |
} else { |
| 459 |
return Promise.reject({status: response.status, data}); |
| 460 |
} |
| 461 |
}); |
| 462 |
}); |
| 463 |
} |
| 464 |
|
| 465 |
When you have axios setup correctly, this is a lot easier:: |
| 466 |
|
| 467 |
function addUser(details) { |
| 468 |
return axios.post('https://api.example.com/user', details); |
| 469 |
} |
| 470 |
|
| 471 |
|
| 472 |
CSRF: Enable protection for session auth, but not token auth |
| 473 |
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 474 |
As mentioned above, CSRF is critical for any mutating operation where the authentication credentials are 'invisibly' sent - such as a session cookie - |
| 475 |
from a browser. But if your endpoint a) can only be authenticated with an attached token or b) can be called either via session OR token; |
| 476 |
it is often desirable not to force token API users to deal with CSRF. To solve this, we need to keep CSRFProtect from checking the csrf-token early in the |
| 477 |
request and instead defer that decision to later decorators/code. Flask-Security's authentication decorators (:func:`.auth_required`, |
| 478 |
:func:`.auth_token_required`, and :func:`.http_auth_required` all support calling csrf protection based on configuration:: |
| 479 |
|
| 480 |
# Disable pre-request CSRF |
| 481 |
app.config["WTF_CSRF_CHECK_DEFAULT"] = False |
| 482 |
|
| 483 |
# Check csrf for session and http auth (but not token) |
| 484 |
app.config["SECURITY_CSRF_PROTECT_MECHANISMS"] = ["session", "basic"] |
| 485 |
|
| 486 |
# Enable CSRF protection |
| 487 |
flask_wtf.CSRFProtect(app) |
| 488 |
|
| 489 |
@app.route("/") |
| 490 |
@auth_required("token", "session") |
| 491 |
def home_page(): |
| 492 |
|
| 493 |
With this configuration, CSRF won't be required if the caller uses an authentication token, but if it uses |
| 494 |
the session cookie it will. |
| 495 |
|
| 496 |
CSRF: Pro-Tips |
| 497 |
++++++++++++++ |
| 498 |
#) Be aware that for CSRF to work, callers MUST send the session cookie. So |
| 499 |
for pure API (token based), and no session cookie - there is no way to support 'login CSRF'. |
| 500 |
So your app must set :py:data:`SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS` |
| 501 |
(or clients must use CSRF/session cookie for logging |
| 502 |
in then once they have an authentication token, no further need for cookie). |
| 503 |
|
| 504 |
#) If you enable CSRFProtect(app) and you want to send request data as JSON, |
| 505 |
then you must include the CSRF token in the header (e.g. X-CSRF-Token) |
| 506 |
|
| 507 |
#) You must enable CSRFProtect(app) if you want to accept the CSRF token in the request |
| 508 |
header. |
| 509 |
|
| 510 |
#) Annotate each of your endpoints with a @auth_required decorator (and don't rely |
| 511 |
on just a @role_required or @login_required decorator) so that Flask-Security |
| 512 |
gets control at the appropriate place. |
| 513 |
|
| 514 |
#) If you can't use a decorator, Flask-Security exposes the underlying method |
| 515 |
:func:`flask_security.handle_csrf`. |
| 516 |
|
| 517 |
#) Consider starting by setting :py:data:`SECURITY_CSRF_IGNORE_UNAUTH_ENDPOINTS` to True. Your |
| 518 |
application likely doesn't need 'login CSRF' protection, and it is frustrating |
| 519 |
to not even be able to login via API! |
| 520 |
|
| 521 |
#) If you have unauthenticated endpoints that you want to protect with CSRF then |
| 522 |
use the :func:`flask_security.unauth_csrf` decorator. |
| 523 |
|
| 524 |
|
| 525 |
.. _axios: https://github.com/axios/axios |
| 526 |
.. _httpClient: https://angular.io/guide/http#security-xsrf-protection |