Debian Codegraph @

docs/features.rst

raw
1 Features
2 ========
3
4 Flask-Security allows you to quickly add common security mechanisms to your
5 Flask application. They include:
6
7
8 Session Based Authentication
9 ----------------------------
10
11 Session based authentication is fulfilled entirely by the `Flask-Login`_
12 extension. Flask-Security handles the configuration of Flask-Login automatically
13 based on a few of its own configuration values and uses Flask-Login's
14 `alternative token`_ feature to associate the value of ``fs_uniquifier`` with the user.
15 (This enables easily invalidating all existing sessions for a given user without
16 having to change their user id). `Flask-WTF`_
17 integrates with the session as well to provide out of the box CSRF support.
18 Flask-Security extends that to support configurations that would require CSRF for requests that are
19 authenticated via session cookies, but not for requests authenticated using tokens.
20
21
22 Role/Identity Based Access
23 --------------------------
24
25 Flask-Security implements very basic role management out of the box. This means
26 that you can associate a high level role or multiple roles to any user. For
27 instance, you may assign roles such as `Admin`, `Editor`, `SuperUser`, or a
28 combination of said roles to a user. Access control is based on the role name and/or
29 permissions contained within the role;
30 and all roles should be uniquely named. This feature is implemented using the
31 `Flask-Principal`_ extension. As with basic RBAC, permissions can be assigned to roles
32 to provide more granular access control. Permissions can be associated with one or
33 more roles (the RoleModel contains a list of permissions). The values of
34 permissions are completely up to the developer - Flask-Security simply treats them
35 as strings.
36 If you'd like to implement even more granular access
37 control (such as per-object), you can refer to the Flask-Principal `documentation on this topic`_.
38
39
40 Password Hashing
41 ----------------
42
43 Password hashing is implemented using `passlib`_. Passwords are hashed with the
44 `argon2`_ function by default but you can easily configure other hashing
45 algorithms.
46 For any given hashing algorithm, consult its documentation on what
47 options/values are recommended. For argon2, the `argon2_cffi`_ package
48 keeps its default options up to date with `RFC9106`_, and should be suitable for most
49 applications. The `OWASP Password Storage Cheat Sheet`_ also
50 has a lot of useful suggestions.
51
52 You should **always use a hashing algorithm** in your production
53 environment. Hash algorithms not listed in :data:`SECURITY_PASSWORD_SINGLE_HASH`
54 will be double hashed - first an HMAC will be computed, then the selected hash
55 function will be used. In this case - you must provide a :data:`SECURITY_PASSWORD_SALT`.
56 A good way to generate this is::
57
58 secrets.SystemRandom().getrandbits(128)
59
60 Bear in mind passlib does not assume which
61 algorithm you will choose and may require additional libraries to be installed.
62
63 Password Validation and Complexity
64 -----------------------------------
65 Consult :ref:`pass_validation_topic`.
66
67
68 Basic HTTP Authentication
69 -------------------------
70
71 Basic HTTP authentication is achievable using a simple view method decorator.
72 This feature expects the incoming authentication information to identify a user
73 in the system. This means that the username must be equal to their email address.
74
75
76 Token Authentication
77 --------------------
78
79 Token based authentication can be used by retrieving the user auth token from an
80 authentication endpoint (e.g. ``/login``, ``/us-signin``, ``/wan-signin``, ``/verify``,
81 ``/us-verify``, ``/wan-verify``).
82 Perform an HTTP POST with a query param of ``include_auth_token`` and the authentication details
83 as JSON data.
84 A successful call will return the authentication token. This token can be used in subsequent
85 requests to protected resources. The auth token should be supplied in the request
86 through an HTTP header or query string parameter. By default the HTTP header
87 name is `Authentication-Token` and the default query string parameter name is
88 `auth_token`.
89
90 Authentication tokens are generated using a uniquifier field in the
91 user's UserModel. By default that field is ``fs_uniquifier``. This means that
92 if that field is changed (via :meth:`.UserDatastore.set_uniquifier`)
93 then any existing authentication tokens will no longer be valid. This value is changed
94 whenever a user changes their password. If this is not the desired behavior then you can add an additional
95 attribute to the UserModel: ``fs_token_uniquifier`` and that will be used instead, thus
96 isolating password changes from authentication tokens. That attribute can be changed via
97 :meth:`.UserDatastore.set_token_uniquifier`. This attribute should have ``unique=True``.
98 Unlike ``fs_uniquifier``, it can be set to ``nullable`` - it will automatically be generated
99 at first use if null.
100
101 Authentication tokens have 2 options for specifying expiry time :data:`SECURITY_TOKEN_MAX_AGE`
102 is applied to ALL authentication tokens. Each authentication token can itself have an embedded
103 expiry value (settable via the :data:`SECURITY_TOKEN_EXPIRE_TIMESTAMP` callable).
104
105 Authentication tokens also convey freshness by recording the time the token was generated.
106 This is used for endpoints protected with :func:`.auth_required` with a ``within``
107 value set.
108
109 .. note::
110 While every Flask-Security endpoint will accept an authentication token header,
111 there are some endpoints that require session information (e.g. a session cookie).
112 This includes entering in a second factor and handling of :ref:`CSRF<csrf_topic>`.
113 As of release 5.5.0, authentication tokens by default carry freshness information.
114
115 User Registration
116 -----------------
117 If :ref:`configured<configuration:Registerable>`, Flask-Security provides a basic user registration view. This view is
118 very simple and new users need only supply an email address and their password.
119 This view can be overridden if your registration process requires more fields.
120 User email is validated and normalized using the
121 `email_validator <https://pypi.org/project/email-validator/>`_ package.
122
123 Username Support
124 -----------------
125 Flask-Security supports configuring and using a ``username`` in addition to or instead of an email for
126 authentication.
127
128 If the :py:data:`SECURITY_USERNAME_ENABLE` configuration option is set to ``True``, ``username``
129 will be added to the register and login forms.
130 By default, the user will be
131 able to authenticate with EITHER email or username - however that can be changed via the
132 :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES`.
133
134 The :py:data:`SECURITY_USERNAME_RECOVERY` option adds an endpoint that allows users
135 to recover a forgotten username (via email).
136
137 The :py:data:`SECURITY_CHANGE_USERNAME` option adds an endpoint that can be
138 used by authenticated users to change their username.
139
140 Email Confirmation
141 ------------------
142 If :ref:`configured<configuration:Confirmable>`, your application
143 can require that new users confirm their email address prior to allowing them to authenticate.
144 Flask-Security will send an email message to any new users with a confirmation
145 link. Upon navigating to the confirmation link, the user's account will be set to
146 'confirmed'. The user can then sign in usually the normal mechanisms.
147 There is also view for resending a confirmation link to a given email
148 if the user happens to try to use an expired token or has lost the previous
149 email. Confirmation links can be configured to expire after a specified amount
150 of time (default 5 days).
151
152 Password Reset/Recovery
153 -----------------------
154 If :ref:`configured<configuration:Recoverable>`,
155 password reset and recovery is available for when a user forgets their
156 password. Flask-Security sends an email to the user with a link to a view which
157 allows them to reset their password. Once the password is reset they are redirected to
158 the login page where they need to authenticate using the new password.
159 Password reset links can be configured to expire after a specified amount of time.
160
161 As with password change - this will update the the user's ``fs_uniquifier`` attribute
162 which will invalidate all existing sessions AND (by default) all authentication tokens.
163
164 Password Change
165 ---------------
166 If :ref:`configured<configuration:Changeable>` users can change their password. Unlike password
167 recovery, this endpoint is used when the user is already authenticated. The result
168 of a successful password change is not only a new password, but a new value for ``fs_uniquifier``.
169 This has the effect of immediately invalidating all existing sessions. The change request
170 itself effectively re-signs in in the user so a new session is created. Note that
171 the same signals are sent as when the user normally authenticates.
172
173 *NOTE*: The ``fs_uniquifier`` by default, controls both sessions and authenticated tokens.
174 Thus changing the password also invalidates all authentication tokens. This may not be desirable
175 behavior, so if the UserModel contains an attribute ``fs_token_uniquifier``, then that will be used
176 when generating authentication tokens and so won't be affected by password changes.
177
178 Two-factor Authentication
179 ----------------------------------------
180 If :ref:`configured<configuration:Two-Factor>`,
181 the two-factor authentication feature generates time-based one time passwords
182 (Tokens). The tokens are generated using the users `totp secret`_, which is unique
183 per user, and is generated both on first login, and when changing the two-factor
184 method (doing this causes the previous totp secret to become invalid). The token
185 is provided by one of 3 methods - email, sms (service is not provided), or
186 an authenticator app such as Google Authenticator, LastPass Authenticator, or Authy.
187 By default, tokens provided by the authenticator app are
188 valid for 2 minutes, tokens sent by mail for up to 5 minute and tokens sent by
189 sms for up to 2 minutes. The QR code used to supply the authenticator app with
190 the secret is generated using the `qrcode <https://pypi.org/project/qrcode/>`_ library.
191 Please read :ref:`2fa_theory_of_operation` for more details.
192
193 The Two-factor feature offers the ability for a user to 'rescue' themselves if
194 they lose track of their secondary factor device. Rescue options include sending
195 a one time code via email, send an email to the application admin, and using a previously
196 generated and downloaded one-time code (see :py:data:`SECURITY_MULTI_FACTOR_RECOVERY_CODES`).
197
198 Unified Sign In
199 ---------------
200 If :ref:`configured<configuration:Unified Signin>`,
201 a generalized login endpoint is provided that takes an `identity`
202 and a `passcode`; where (based on configuration):
203
204 * `identity` is any of :py:data:`SECURITY_USER_IDENTITY_ATTRIBUTES` (e.g. email, username, phone)
205 * `passcode` is a password or a one-time code (delivered via email, SMS, or authenticator app)
206
207 Please see this `Wikipedia`_ article about multi-factor authentication.
208
209 Using this feature, it is possible to not require the user to have a stored password
210 at all, and just require the use of a one-time code. The mechanisms for generating
211 and delivering the one-time code are similar to common two-factor mechanisms.
212
213 This one-time code can be configured to be delivered via email, SMS or authenticator app -
214 however be aware that NIST does not recommend email for this purpose (though many web sites do so)
215 due to the fact that a) email may travel through
216 many different servers as part of being delivered - and b) is available from any device.
217
218 Using SMS or an authenticator app means you are providing "something you have" (the mobile device)
219 and either "something you know" (passcode to unlock your device)
220 or "something you are" (biometric quality to unlock your device).
221 This effectively means that using a one-time code to sign in, is in fact already two-factor (if using
222 SMS or authenticator app). Many large authentication providers already offer this - here is
223 `Microsoft's`_ version.
224
225 Note that by configuring :py:data:`SECURITY_US_ENABLED_METHODS` an application can
226 use this endpoint JUST with identity/password or in fact disallow passwords altogether.
227
228 Unified sign in is integrated with two-factor authentication. Since in general
229 there is no need for a second factor if the initial authentication was with SMS or
230 an authenticator application, the :py:data:`SECURITY_US_MFA_REQUIRED` configuration
231 determines which primary authentication mechanisms require a second factor. By default
232 limited to ``email`` and ``password`` (if two-factor is enabled).
233
234 Be aware that by default, the :py:data:`SECURITY_US_SETUP_URL` endpoint is protected
235 with a freshness check (see :meth:`flask_security.auth_required`) which means it requires a session
236 cookie to function properly. This is true even if using JSON payload or token authentication.
237 If you disable the freshness check then sessions aren't required.
238
239 `Current Limited Functionality`:
240
241 * Change password does not work if a user registers without a password. However
242 forgot-password will allow the user to set a new password.
243 * Registration and Confirmation only work with email - so while you can enable multiple
244 authentication methods, you still have to register with email.
245
246 WebAuthn/Passkeys
247 -----------------
248 **This feature is in Beta - mostly due to it being brand new and little to no production soak time**
249
250 WebAuthn is a standardized protocol that connects authenticators (such as YubiKey and mobile biometrics)
251 with websites. If :ref:`configured<configuration:WebAuthn>`, Flask-Security supports using WebAuthn credentials (aka passkeys) as either 'first' or 'secondary'
252 authenticators. Please read :ref:`webauthn_topic` for more details.
253
254 Email Change
255 ------------
256 If :ref:`configured<configuration:Change-Email>`, users can change the email they registered with. This will send a new confirmation email to the new email address.
257
258 Login Tracking
259 --------------
260 Flask-Security can, if :ref:`configured<configuration:Trackable>`, keep track of basic login events and
261 statistics. They include:
262
263 * Last login date
264 * Current login date
265 * Last login IP address
266 * Current login IP address
267 * Total login count
268
269 JSON/Ajax Support
270 -----------------
271 Flask-Security supports JSON/Ajax requests where appropriate. Please
272 look at :ref:`csrf_topic` for details on how to work with JSON and
273 Single Page Applications.
274
275 In addition, :ref:`spa:Working With Single Page Applications`
276 (like those built with Vue, Angular, and React) are supported via customizable redirect links.
277
278 Command Line Interface
279 ----------------------
280 Basic `Click`_ commands for managing users and roles are automatically
281 registered. They can be completely disabled or their names can be changed.
282 Run ``flask --help`` and look for users and roles.
283
284
285 Social Login (OAuth) Authentication
286 ------------------------------------
287 Flask-Security provides a thin layer which integrates `authlib`_ with Flask-Security
288 views and features (such as two-factor authentication and verify). Flask-Security is shipped
289 with support for github and google - others can be added by the application (see `loginpass`_
290 for many examples).
291
292 See :py:class:`flask_security.OAuthGlue` and :py:class:`flask_security.FsOAuthProvider`
293
294 Please note - this is for authentication only, and the authenticating user must
295 already be a registered user in your application. Once authenticated, all further
296 authorization uses Flask-Security role/permission mechanisms.
297
298 See `Flask OAuth Client <https://docs.authlib.org/en/latest/client/flask.html>`_
299 for details. Note in particular, that you must setup and provide provider specific
300 information - and most importantly - XX_CLIENT_ID and XX_CLIENT_SECRET should be
301 specified as environment variables.
302
303 We have seen issues with some providers when `SESSION_COOKIE_SAMESITE` = "strict".
304 The handshake (sometimes just the first time when the user is being asked to accept your application)
305 fails due to the session cookie not getting sent as part of the redirect.
306
307 A very simple example of configuring social login with Flask-Security is available
308 in the `examples` directory.
309
310 Account Management
311 -------------------
312 Flask-Security includes support for managing user accounts. A combination of forms
313 views, database models, and CLI provide application support for:
314
315 Adding and Deleting Users
316 +++++++++++++++++++++++++
317 Users can be added either by enabling the Register feature - which allows users to self-register
318 and/or via CLI - where an administrator can control precisely who to add to the system.
319 Users can be allowed or required to have a username in addition to an email address.
320
321 Self-Management of Accounts
322 +++++++++++++++++++++++++++
323 Flask-Security can be configured to allow users to perform many normal administrative
324 tasks pertaining to security:
325
326 * :ref:`Change Password<features:Password Change>`
327 * :ref:`Forgot Password<features:Password Reset/Recovery>`
328 * :ref:`Change Username<features:Username Support>`
329 * :ref:`Forgot Username<features:Username Support>`
330 * :ref:`Change Email<features:Email Change>`
331 * Add/modify alternative primary authentication mechanisms -
332 SMS, Passkeys, Authenticator, magic link, social login (OAuth)
333 * Add/modify second factor authentication mechanisms -
334 SMS, Passkeys, Authenticator, magic link
335
336 Administrative Management of Accounts
337 ++++++++++++++++++++++++++++++++++++++
338 The CLI and API provides administrators and the application control over accounts.
339
340 * Deactivate immediately stops any access by the user to any
341 protected endpoints
342
343 * CLI: ``user deactivate``
344 * API: :py:meth:`.UserDatastore.deactivate_user`
345 * Reset user access - this disables all authentication mechanisms except password
346 (e.g. one-time password, passkeys, tokens)
347
348 * CLI: ``user reset_access``
349 * API: :py:meth:`.UserDatastore.reset_user_access`
350 * Create or delete roles - including adding/removing permissions from roles
351
352 * CLI: ``roles create``, ``roles add_permissions``, ``roles remove_permissions``
353 * API: :py:meth:`.UserDatastore.create_role`, :py:meth:`.UserDatastore.add_permissions_to_role`, :py:meth:`.UserDatastore.remove_permissions_from_role`
354 * Add or remove roles from a user
355
356 * CLI: ``roles add``, ``roles remove``
357 * API: :py:meth:`.UserDatastore.add_role_to_user`, :py:meth:`.UserDatastore.remove_role_from_user`
358 * API - :ref:`Signals<api:Signals>` are sent for many operations that allow the application to track
359 important account changes (such as track_failed_authn)
360 * Configuration - allow or require two factor authentication
361 * API - :py:meth:`.UserMixin.check_tf_required` allows applications to fine-tune which users require MFA.
362 For example could require all users with a role of 'admin' to setup MFA.
363 * API - :py:meth:`.UserMixin.is_locked` can be used to support account lockout
364
365
366 .. _Click: https://palletsprojects.com/p/click/
367 .. _Flask-Login: https://flask-login.readthedocs.org/en/latest/
368 .. _Flask-WTF: https://flask-wtf.readthedocs.io/en/1.2.x/csrf/
369 .. _alternative token: https://flask-login.readthedocs.io/en/latest/#alternative-tokens
370 .. _Flask-Principal: https://pypi.org/project/Flask-Principal/
371 .. _documentation on this topic: http://packages.python.org/Flask-Principal/#granular-resource-protection
372 .. _passlib: https://passlib.readthedocs.io/en/stable/
373 .. _totp secret: https://passlib.readthedocs.io/en/stable/narr/totp-tutorial.html#overview
374 .. _argon2: https://en.wikipedia.org/wiki/Argon2
375 .. _argon2_cffi: https://pypi.org/project/argon2-cffi/
376 .. _RFC9106: https://www.rfc-editor.org/rfc/rfc9106.html
377 .. _OWASP Password Storage Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html
378 .. _bcrypt: https://en.wikipedia.org/wiki/Bcrypt
379 .. _PyQRCode: https://pypi.python.org/pypi/PyQRCode/
380 .. _Wikipedia: https://en.wikipedia.org/wiki/Multi-factor_authentication
381 .. _Microsoft's: https://docs.microsoft.com/en-us/azure/active-directory/user-help/user-help-auth-app-overview
382 .. _authlib: https://authlib.org/
383 .. _loginpass: https://github.com/authlib/loginpass