Debian Codegraph @

docs/customizing.rst

raw
1 Customizing
2 ===========
3
4 Flask-Security bootstraps your application with various views for handling its
5 configured features to get you up and running as quickly as possible. However,
6 you'll probably want to change the way these views look to be more in line with
7 your application's visual design.
8
9
10 Views
11 -----
12
13 Flask-Security is packaged with a default template for each view it presents to
14 a user. Templates are located within a subfolder named ``security``. The
15 following is a list of view templates:
16
17 * `security/forgot_password.html`
18 * `security/login_user.html`
19 * `security/logout_user.html`
20 * `security/mf_recovery.html`
21 * `security/mf_recovery_codes.html`
22 * `security/recover_username.html`
23 * `security/register_user.html`
24 * `security/reset_password.html`
25 * `security/change_password.html`
26 * `security/change_email.html`
27 * `security/change_username.html`
28 * `security/send_confirmation.html`
29 * `security/send_login.html`
30 * `security/verify.html`
31 * `security/two_factor_select.html`
32 * `security/two_factor_setup.html`
33 * `security/two_factor_verify_code.html`
34 * `security/us_signin.html`
35 * `security/us_setup.html`
36 * `security/us_verify.html`
37 * `security/wan_register.html`
38 * `security/wan_signin.html`
39 * `security/wan_verify.html`
40
41 Overriding these templates is simple:
42
43 1. Create a folder named ``security`` within your application's templates folder
44 2. Create a template with the same name for the template you wish to override
45
46 You can also specify custom template file paths in the :doc:`configuration <configuration>`.
47
48 Each template is passed a template context object that includes the following,
49 including the objects/values that are passed to the template by the main
50 Flask application context processor:
51
52 * ``<template_name>_form``: A form object for the view.
53 * ``security``: The Flask-Security extension object.
54 * ``config``: Injected by Flask - this holds all extensions' configuration.
55 * ``url_for_security``: A function that returns the configured URL for the passed Security endpoint.
56 * ``_fsdomain``: A function used to `tag` strings for extraction and localization.
57 * ``_fs_is_user_authenticated``: Returns True if argument (user) is authenticated.
58 Usually the `current_user` proxy is the appropriate argument.
59
60 To add more values to the template context, you can specify a context processor
61 for all views or a specific view. For example::
62
63 security = Security(app, user_datastore)
64
65 # This processor is added to all templates
66 @security.context_processor
67 def security_context_processor():
68 return dict(hello="world")
69
70 # This processor is added to only the register view
71 @security.register_context_processor
72 def security_register_processor():
73 return dict(something="else")
74
75 The following is a list of all the available context processor decorators:
76
77 * ``context_processor``: All views
78 * ``forgot_password_context_processor``: Forgot password view
79 * ``login_context_processor``: Login view
80 * ``logout_context_processor``: Logout view
81 * ``mf_recovery_codes_context_processor``: Setup recovery codes view
82 * ``mf_recovery_context_processor``: Use recovery code view
83 * ``register_context_processor``: Register view
84 * ``reset_password_context_processor``: Reset password view
85 * ``change_password_context_processor``: Change password view
86 * ``change_email_context_processor``: Change email view
87 * ``change_username_context_processor``: Change username view
88 * ``send_confirmation_context_processor``: Send confirmation view
89 * ``send_login_context_processor``: Send login view
90 * ``mail_context_processor``: Whenever an email will be sent
91 * ``tf_select_context_processor``: Two factor select view
92 * ``tf_setup_context_processor``: Two factor setup view
93 * ``tf_token_validation_context_processor``: Two factor token validation view
94 * ``us_signin_context_processor``: Unified sign in view
95 * ``us_setup_context_processor``: Unified sign in setup view
96 * ``us_verify_context_processor``: Unified sign in verify view
97 * ``verify_context_processor``: Verify view
98 * ``wan_register_context_processor``: WebAuthn registration view
99 * ``wan_signin_context_processor``: WebAuthn sign in view
100 * ``wan_verify_context_processor``: WebAuthn verify view
101
102
103 Forms
104 -----
105
106 All forms can be overridden. For each form used, you can specify a
107 replacement class. This allows you to add extra fields to any
108 form or override validators. For example it is often desired to add additional
109 personal information fields to the registration form::
110
111 from flask_security import RegisterFormV2
112 from wtforms import StringField
113 from wtforms.validators import DataRequired
114
115 class ExtendedRegisterForm(RegisterFormV2):
116 first_name = StringField('First Name', [DataRequired()])
117 last_name = StringField('Last Name', [DataRequired()])
118
119 security = Security(app, user_datastore,
120 register_form=ExtendedRegisterForm)
121
122 For the ``register_form`` and ``confirm_register_form``, only fields that
123 exist in the user model are passed (as kwargs) to :meth:`.UserDatastore.create_user`.
124 Thus, in the above case, the ``first_name`` and ``last_name`` fields will only
125 be passed if the model looks like::
126
127 class User(db.Model, UserMixin):
128 id = db.Column(db.Integer, primary_key=True)
129 email = db.Column(db.String(255), unique=True)
130 password = db.Column(db.String(255))
131 first_name = db.Column(db.String(255))
132 last_name = db.Column(db.String(255))
133
134 .. warning::
135 Adding fields is fine - however re-defining existing fields could cause
136 various views to no longer function. Many fields have complex (and not
137 publicly exposed) validators that have side effects.
138
139 .. warning::
140 It is important to ALWAYS subclass the base Flask-Security form and not
141 attempt to just redefine the class. This is due to the validation method
142 of many of the forms performs critical additional validation AND will change
143 or add values to the form as a side-effect. See below for how to do this.
144
145 If you need to override an existing field in a form (to override/add validators),
146 and you want to define a re-usable validator - use multiple inheritance - be extremely
147 careful about the order of the inherited classes::
148
149 from wtforms import PasswordField, ValidationError
150 from wtforms.validators import DataRequired
151 from flask_security import RegisterFormV2
152
153 def password_validator(form, field):
154 if field.data.startswith("PASS"):
155 raise ValidationError("Really - don't start a password with PASS")
156
157 class NewPasswordFormMixinEx:
158 password = PasswordField("password",
159 validators=[DataRequired(message="PASSWORD_NOT_PROVIDED"),
160 password_validator])
161
162 class MyRegisterForm(NewPasswordFormMixinEx, RegisterFormV2):
163 pass
164
165 app.config["SECURITY_REGISTER_FORM"] = MyRegisterForm
166
167 The following is a list of all the available form overrides:
168
169 * ``login_form``: Login form (:py:class:`flask_security.LoginForm`)
170 * ``logout_form``: Logout form (:py:class:`flask_security.LogoutForm`)
171 * ``verify_form``: Verify form
172 * ``confirm_register_form``: Confirmable register form (:py:class:`flask_security.ConfirmRegisterForm`) (deprecated)
173 * ``register_form``: Register form (:py:class:`flask_security.RegisterForm` (deprecated) OR (:py:class:`flask_security.RegisterFormV2`)
174 * ``forgot_password_form``: Forgot password form
175 * ``reset_password_form``: Reset password form
176 * ``change_password_form``: Change password form
177 * ``change_email_form``: Change email form
178 * ``change_username_form``: Change username form (:py:class:`flask_security.ChangeUsernameForm`)
179 * ``send_confirmation_form``: Send confirmation form
180 * ``mf_recovery_codes_form``: Setup recovery codes form
181 * ``mf_recovery_form``: Use recovery code form
182 * ``passwordless_login_form``: Passwordless login form
183 * ``refresh_token_form``: Refresh Token form (:py:class:`flask_security.RefreshTokenForm`)
184 * ``two_factor_verify_code_form``: Two-factor verify code form
185 * ``two_factor_select_form``: Two-factor select form
186 * ``two_factor_setup_form``: Two-factor setup form
187 * ``two_factor_rescue_form``: Two-factor help user form
188 * ``us_signin_form``: Unified sign in form
189 * ``us_setup_form``: Unified sign in setup form
190 * ``us_setup_validate_form``: Unified sign in setup validation form
191 * ``us_verify_form``: Unified sign in verify form
192 * ``username_recovery_form``: Username recovery form
193 * ``wan_delete_form``: WebAuthn delete a registered key form
194 * ``wan_register_form``: WebAuthn initiate registration ceremony form
195 * ``wan_register_response_form``: WebAuthn registration ceremony form
196 * ``wan_signin_form``: WebAuthn initiate sign in ceremony form
197 * ``wan_signin_response_form``: WebAuthn sign in ceremony form
198 * ``wan_verify_form``: WebAuthn verify form
199
200 .. tip::
201 Changing/extending the form class won't directly change how it is displayed.
202 You need to ALSO provide your own template and explicitly add the new fields you want displayed.
203
204 .. _register_form_migration:
205
206 Register Form Migration
207 ++++++++++++++++++++++++
208 Since early in Flask Security releases, there have been 2 different forms used for
209 registration: RegisterForm and ConfirmRegisterForm. The only difference between them is
210 that the ConfirmRegisterForm doesn't require password confirmation (i.e. asking the user to
211 re-type their password). This wasn't a config option but rather based on whether :py:data:`SECURITY_CONFIRMABLE` was
212 set or whether the request was form-based or JSON. This has always been a huge source of
213 confusion. A new :py:class:`flask_security.RegisterFormV2` has been introduced that replaces both
214 of the older forms. Since this is a breaking change, it is being implemented in phases.
215
216 In release 5.6 the new form: RegisterFormV2 is available for use. By default the existing
217 forms are used - so there are no backwards compatibility issues. However, subclassing RegisterForm or
218 ConfirmRegisterForm will raise a deprecation warning. The new RegisterFormV2 can be used in one of 2 ways:
219
220 - set :py:data:`SECURITY_USE_REGISTER_V2` to ``True``
221 - subclass RegisterFormV2 and use that as the 'register_form` argument to the
222 Flask Security constructor.
223
224 The new RegisterFormV2 will add a ``password_confirm`` field if :py:data:`SECURITY_PASSWORD_CONFIRM_REQUIRED`
225 is set to ``True`` (the default). Additionally, JSON requests will need to provide a value for ``password_confirm``
226 if configured.
227
228 In release 5.7 the default is flipped - :py:data:`SECURITY_USE_REGISTER_V2` is ``True`` and RegisterFormV2 is the default form.
229
230 .. _form_instantiation:
231
232 Controlling Form Instantiation
233 ++++++++++++++++++++++++++++++
234 This is an advanced concept! Please see :meth:`.Security.set_form_info` and
235 :class:`.FormInfo`.
236
237 This is an example of providing your own form instantiator using the 'form clone' pattern.
238 In this example we are injecting an external `service` into the form for use in validation::
239
240 from flask_security import FormInfo
241
242 class MyLoginForm(LoginForm):
243 def __init__(self, *args, service=None, **kwargs):
244 super().__init__(*args, **kwargs)
245 self.myservice = service
246
247 def instantiator(self, form_name, form_cls, *args, **kwargs):
248 return MyLoginForm(*args, service=self.myservice, **kwargs)
249
250 def validate(self, **kwargs: t.Any) -> bool:
251 if not super().validate(**kwargs): # pragma: no cover
252 return False
253 if not self.myservice(self.email.data):
254 self.email.errors.append("Not happening")
255 return False
256 return True
257
258 # A silly service that only allows 'matt'' log in!
259 def login_checker(email):
260 return True if email == "[email protected]" else False
261
262 with app.test_request_context():
263 # Flask-WTForms require a request context.
264 fi = MyLoginForm(formdata=None, service=login_checker)
265 app.security.set_form_info("login_form", FormInfo(fi.instantiator))
266
267 .. _custom_login_form:
268
269 Customizing the Login Form
270 ++++++++++++++++++++++++++
271 This is an example of how to modify the registration and login form to add support for
272 a single input field to accept both email and username (mimicking legacy Flask-Security behavior).
273 Flask-Security supports username as a configuration option so this is not strictly needed
274 any more, however, Flask-Security's LoginForm uses 2 different input fields (so that
275 appropriate input attributes can be set)::
276
277 from flask_security import (
278 RegisterForm,
279 LoginForm,
280 Security,
281 lookup_identity,
282 uia_username_mapper,
283 unique_identity_attribute,
284 )
285 from werkzeug.local import LocalProxy
286 from wtforms import StringField, ValidationError, validators
287
288 def username_validator(form, field):
289 # Side-effect - field.data is updated to normalized value.
290 # Use proxy to we can declare this prior to initializing Security.
291 _security = LocalProxy(lambda: app.extensions["security"])
292 msg, field.data = _security.username_util.validate(field.data)
293 if msg:
294 raise ValidationError(msg)
295
296 class MyRegisterForm(RegisterForm):
297 # Note that unique_identity_attribute uses the defined field 'mapper' to
298 # normalize. We validate before that to give better error messages and
299 # to set the normalized value into the form for saving.
300 username = StringField(
301 "Username",
302 validators=[
303 validators.data_required(),
304 username_validator,
305 unique_identity_attribute,
306 ],
307 )
308
309 class MyLoginForm(LoginForm):
310 email = StringField("email", [validators.data_required()])
311
312 def validate(self, **kwargs):
313 self.user = lookup_identity(self.email.data)
314 # Setting 'ifield' informs the default login form validation
315 # handler that the identity has already been confirmed.
316 self.ifield = self.email
317 if not super().validate(**kwargs):
318 return False
319 return True
320
321 # Allow registration with email, but login only with username
322 app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"] = [
323 {"username": {"mapper": uia_username_mapper}}
324 ]
325 security = Security(
326 datastore=sqlalchemy_datastore,
327 register_form=MyRegisterForm,
328 login_form=MyLoginForm,
329 )
330 security.init_app(app)
331
332 Localization
333 ------------
334 All messages, form labels, and form strings are localizable. Flask-Security uses
335 `Flask-Babel <https://pypi.org/project/Flask-Babel/>`_ to manage its messages.
336
337 .. tip::
338 Be sure to explicitly initialize your babel extension::
339
340 import flask_babel
341
342 flask_babel.Babel(app)
343
344 All translations are tagged with a domain, as specified by the configuration variable
345 ``SECURITY_I18N_DOMAIN`` (default: "flask_security"). For messages and labels all this
346 works seamlessly. For strings inside templates it is necessary to explicitly ask for
347 the "flask_security" domain, since your application itself might have its own domain.
348 Flask-Security places the method ``_fsdomain`` in jinja2's global environment and
349 uses that in all templates.
350 In order to reference a Flask-Security translation from ANY template (such as if you copied and
351 modified an existing security template) just use that method::
352
353 {{ _fsdomain("Login") }}
354
355 Be aware that Flask-Security will validate and normalize email input using the
356 `email_validator <https://pypi.org/project/email-validator/>`_ package.
357 The normalized form is stored in the DB.
358
359 Using Humanize
360 ++++++++++++++
361
362 Some Flask-Security configuration variables (e.g. all the _WITHIN ones) are defined using
363 timedelta. These variables are used in various error messages and email templates. In order to
364 localize those portions of the message, Flask-Security uses humanize.precisedelta if
365 `humanize <https://humanize.readthedocs.io/>`_ is
366 installed - otherwise it uses an internal utility that always returns English.
367 It is up to the application to properly configure humanize (via a call to humanize.i18n.activate(<locale>).
368
369 Overriding Messages
370 ++++++++++++++++++++
371
372 It is possible to change one or more messages (either the original default english
373 and/or a specific translation). Adding the following to your app::
374
375 app.config["SECURITY_MSG_INVALID_PASSWORD"] = ("Password no-worky", "error")
376
377 will change the default message in english.
378
379 .. tip::
380 The string messages themselves are a 'key' into the translation .po/.mo files.
381 Do not pass in gettext('string') or lazy_gettext('string).
382
383 If you need translations then you
384 need to create your own ``translations`` directory and add the appropriate .po files
385 and compile them. Finally, add your translations directory path to the configuration.
386 In this example, create a file ``flask_security.po`` under a directory:
387 ``translations/fr_FR/LC_MESSAGES`` (for french) with the following contents::
388
389 msgid ""
390 msgstr ""
391
392 msgid "Password no-worky"
393 msgstr "Passe - no-worky"
394
395
396 Then compile it with::
397
398 pybabel compile -d translations/ -i translations/fr_FR/LC_MESSAGES/flask_security.po -l fr_FR -D flask_security
399
400 Finally add your translations directory to your configuration::
401
402 app.config["SECURITY_I18N_DIRNAME"] = ["builtin", "translations"]
403
404 .. _emails_topic:
405
406 Emails
407 ------
408
409 Flask-Security is also packaged with a default template for each email that it
410 may send. The default templates are located within the subfolder named ``security/email``.
411 Each template has a both a text and an html version (see :py:data:`SECURITY_EMAIL_HTML`)
412
413 The following is a list of email templates:
414
415 * :py:data:`SECURITY_CHANGE_EMAIL_EMAIL_TEMPLATE` ``"security/email/change_email_instructions"``
416 * :py:data:`SECURITY_EMAIL_TEMPLATE_PASSWORD_CHANGE_NOTICE` ``"security/email/change_notice"``
417 * :py:data:`SECURITY_EMAIL_TEMPLATE_CONFIRM` ``"security/email/confirmation_instructions"``
418 * :py:data:`SECURITY_EMAIL_TEMPLATE_PASSWORD_RESET` ``"security/email/reset_instructions"``
419 * :py:data:`SECURITY_EMAIL_TEMPLATE_PASSWORD_RESET_NOTICE` ``"security/email/reset_notice"``
420 * :py:data:`SECURITY_EMAIL_TEMPLATE_PASSWORDLESS` ``"security/email/login_instructions"``
421 * :py:data:`SECURITY_REGISTER_EMAIL_TEMPLATE` ``"security/email/welcome"``
422 * :py:data:`SECURITY_REGISTER_EMAIL_EXISTING_USERNAME_TEMPLATE` ``"security/email/welcome_existing_username"``
423 * :py:data:`SECURITY_REGISTER_EMAIL_EXISTING_TEMPLATE` ``"security/email/welcome_existing"``
424 * :py:data:`SECURITY_TWO_FACTOR_EMAIL_TEMPLATE` ``"security/email/two_factor_instructions"``
425 * :py:data:`SECURITY_TWO_FACTOR_RESCUE_EMAIL_TEMPLATE` ``"security/email/two_factor_rescue"``
426 * :py:data:`SECURITY_US_EMAIL_TEMPLATE` ``"security/email/us_instructions"``
427 * :py:data:`SECURITY_CHANGE_USERNAME_EMAIL_TEMPLATE` ``"security/email/change_username_notice"``
428 * :py:data:`SECURITY_USERNAME_RECOVERY_EMAIL_TEMPLATE` ``"security/email/username_recovery"``
429
430 Overriding these templates is simple:
431
432 1. Create a folder named ``security/email`` within your application's templates folder
433 2. Create a template with the same name for the template you wish to override
434
435 OR
436
437 1. Change the above configuration variable to point to a template in your applications template path(s).
438
439 Each template is passed a template context object that includes values as described in the table below.
440 In addition, all templates receive:
441
442 * ``security``: The Flask-Security extension object.
443 * ``config``: Injected by Flask - this holds all extensions' configuration.
444 The template can retrieve any configuration variable using e.g. ``{{ config["SECURITY_XXX"] }}``
445
446 If you require more values in the
447 templates, you can specify an email context processor with the
448 ``mail_context_processor`` decorator. For example::
449
450 security = Security(app, user_datastore)
451
452 # This processor is added to all emails
453 @security.mail_context_processor
454 def security_mail_processor():
455 return dict(hello="world")
456
457
458 There are many configuration variables associated with emails, and each template
459 will receive a slightly different context. The ``Gate Config`` column are configuration variables that if set
460 to ``False`` will bypass sending of the email (they all default to ``True``).
461 In most cases, in addition to an email being sent, a :ref:`Signal <signals_topic>` is sent.
462 The table below summarizes all this:
463
464 ============================= =================================== ============================================= ====================== ===============================
465 **Template Name** **Gate Config** **Subject Config** **Context Vars** **Signal Sent**
466 ----------------------------- ----------------------------------- --------------------------------------------- ---------------------- -------------------------------
467 welcome SECURITY_SEND_REGISTER_EMAIL SECURITY_EMAIL_SUBJECT_REGISTER - user user_registered
468 - confirmation_link
469 - confirmation_token
470 confirmation_instructions N/A SECURITY_EMAIL_SUBJECT_CONFIRM - user confirm_instructions_sent
471 - confirmation_link
472 - confirmation_token
473 - within
474 change_email_instructions N/A SECURITY_CHANGE_EMAIL_SUBJECT - user change_email_instructions_sent
475 - link
476 - token
477 - within
478 login_instructions N/A SECURITY_EMAIL_SUBJECT_PASSWORDLESS - user login_instructions_sent
479 - login_link
480 - login_token
481 reset_instructions SEND_PASSWORD_RESET_EMAIL SECURITY_EMAIL_SUBJECT_PASSWORD_RESET - user reset_password_instructions_sent
482 - reset_link
483 - reset_token
484 - within
485 reset_notice SEND_PASSWORD_RESET_NOTICE_EMAIL SECURITY_EMAIL_SUBJECT_PASSWORD_NOTICE - user password_reset
486
487 change_notice SEND_PASSWORD_CHANGE_EMAIL SECURITY_EMAIL_SUBJECT_PASSWORD_CHANGE_NOTICE - user password_changed
488 change_username_notice SEND_USERNAME_PASSWORD_CHANGE_EMAIL SECURITY_EMAIL_SUBJECT_USERNAME_CHANGE_NOTICE - user username_changed
489 - old_username
490 two_factor_instructions N/A SECURITY_EMAIL_SUBJECT_TWO_FACTOR - user tf_security_token_sent
491 - token
492 - username
493 - within
494 two_factor_rescue N/A SECURITY_EMAIL_SUBJECT_TWO_FACTOR_RESCUE - user N/A
495 us_instructions N/A SECURITY_US_EMAIL_SUBJECT - user us_security_token_sent
496 - login_token
497 - login_link
498 - username
499 - within
500 welcome_existing SECURITY_SEND_REGISTER_EMAIL SECURITY_EMAIL_SUBJECT_REGISTER - user user_not_registered
501 SECURITY_RETURN_GENERIC_RESPONSES - recovery_link
502 - confirmation_link
503 - confirmation_token
504 - reset_link
505 - reset_token
506 welcome_existing_username SECURITY_SEND_REGISTER_EMAIL SECURITY_EMAIL_SUBJECT_REGISTER - email user_not_registered
507 SECURITY_RETURN_GENERIC_RESPONSES - username
508 username_recovery SECURITY_USERNAME_RECOVERY SECURITY_EMAIL_SUBJECT_USERNAME_RECOVERY - user username_recovery_email_sent
509 - username
510 ============================= =================================== ============================================= ====================== ===============================
511
512 When sending an email, Flask-Security goes through the following steps:
513
514 #. Calls the email context processor as described above
515
516 #. Calls ``render_template`` (as configured at Flask-Security initialization time) with the
517 context and template to produce a text and/or html version of the message
518
519 #. Calls :meth:`.MailUtil.send_mail` with all the required parameters.
520
521 The default implementation of ``MailUtil.send_mail`` uses Flask-Mail to create and send the message.
522 By providing your own implementation, you can use any available python email handling package.
523
524 Email subjects are by default localized - see above section on Localization to learn how
525 to customize them.
526
527 Emails with Celery
528 ++++++++++++++++++
529
530 Sometimes it makes sense to send emails via a task queue, such as `Celery`_.
531 This is supported by providing your own implementation of the :class:`.MailUtil` class::
532
533 from flask_security import MailUtil
534 class MyMailUtil(MailUtil):
535
536 def send_mail(self, template, subject, recipient, sender, body, html, **kwargs):
537 send_flask_mail.delay(
538 subject=subject,
539 from_email=sender,
540 to=[recipient],
541 body=body,
542 html=html,
543 )
544
545 Then register your class as part of Flask-Security initialization::
546
547 from flask import Flask
548 from flask_mailman import EmailMultiAlternatives, Mail
549 from flask_security import Security, SQLAlchemyUserDatastore
550 from celery import Celery
551
552 mail = Mail()
553 security = Security()
554 celery = Celery()
555
556
557 @celery.task
558 def send_flask_mail(**kwargs):
559 with app.app_context():
560 with mail.get_connection() as connection:
561 html = kwargs.pop("html", None)
562 msg = EmailMultiAlternatives(**kwargs, connection=connection)
563 if html:
564 msg.attach_alternative(html, "text/html")
565 msg.send()
566
567 def create_app(config):
568 """Initialize Flask instance."""
569
570 app = Flask(__name__)
571 app.config.from_object(config)
572
573 mail.init_app(app)
574 datastore = SQLAlchemyUserDatastore(db, User, Role)
575 security.init_app(app, datastore, mail_util_cls=MyMailUtil)
576
577 return app
578
579 .. _Celery: http://www.celeryproject.org/
580
581
582 .. _responsetopic:
583
584 Responses
585 ---------
586 Flask-Security will likely be a very small piece of your application,
587 so Flask-Security makes it easy to override all aspects of API responses.
588
589 JSON Response
590 +++++++++++++
591 Applications that support a JSON based API need to be able to have a uniform
592 API response. Flask-Security has a default way to render its API responses - which can
593 be easily overridden by providing a callback function via :meth:`.Security.render_json`.
594 Be aware that Flask-Security subclasses Flask's JSONProvider interface and sets
595 it on `app.json_provider_cls`.
596
597 401, 403, Oh My
598 +++++++++++++++
599 For a very long read and discussion; look at `this`_. Out of the box, Flask-Security in
600 tandem with Flask-Login, behaves as follows:
601
602 * If authentication fails as the result of a `@login_required`, `@auth_required("session", "token")`,
603 or `@token_auth_required` then if the request 'wants' a JSON
604 response, :meth:`.Security.render_json` is called with a 401 status code.
605 If not then the `SECURITY_MSG_UNAUTHENTICATED` message is flashed and the request is
606 redirected to the `login` view.
607
608 * If authentication fails as the result of a `@http_auth_required` or `@auth_required("basic")`
609 then a 401 is returned along with the http header ``WWW-Authenticate`` set to
610 ``Basic realm="xxxx"``. The realm name is defined by :py:data:`SECURITY_DEFAULT_HTTP_AUTH_REALM`.
611
612 * If authorization fails as the result of `@roles_required`, `@roles_accepted`,
613 `@permissions_required`, or `@permissions_accepted`, then :meth:`.Security.unauthz_handler` is called.
614 The default implementation flow is: if the request 'wants' a JSON
615 response, :meth:`.Security.render_json` is called with a 403 status code. If not,
616 then if :py:data:`SECURITY_UNAUTHORIZED_VIEW` is defined, the response will redirected.
617 If :py:data:`SECURITY_UNAUTHORIZED_VIEW` is not defined, then ``abort(403)`` is called.
618
619 All this can be easily changed by registering any or all of :meth:`.Security.render_json`,
620 :meth:`.Security.unauthn_handler` and :meth:`.Security.unauthz_handler`.
621
622 The decision on whether to return JSON is based on:
623
624 * Was the request content-type "application/json" (e.g. request.is_json()) OR
625
626 * Is the 'best' value of the ``Accept`` HTTP header "application/json"
627
628
629 .. _`this`: https://stackoverflow.com/questions/3297048/403-forbidden-vs-401-unauthorized-http-responses
630
631
632 Redirects
633 ---------
634 Flask-Security uses redirects frequently (when using forms), and most of the redirect
635 destinations are configurable. When Flask-Security initiates a redirect it (almost) always flashes a message
636 that provides some context for the user.
637 In addition, Flask-Security - both in its views and default templates, attempts to propagate
638 any `next` query param and in fact, an existing `?next=/xx` will override most of the configuration redirect URLs.
639
640 As a complex example consider an unauthenticated user accessing a `@auth_required` endpoint, and the user has
641 two-factor authentication set up.:
642
643 * GET("/protected") - The `default_unauthn_handler` will redirect to ``/login?next=/protected``
644 * The login form/template will pick any `?next=/xx` argument off the request URL and append it to form action.
645 * When the form is submitted if will do a POST("/login?next=/protected")
646 * Assuming correct authentication, the system will send out a 2-factor code and redirect to ``/tf-verify?next=/protected``
647 * The two_factor_validation_form/template also pulls any `?next=/xx` and appends to the form action.
648 * When the `tf-validate` form is submitted it will do a POST("/tf-validate?next=/protected").
649 * Assuming a correct code, the user is authenticated and is redirected. That redirection first
650 looks for a 'next' in the request.args then in request.form and finally will use the value of :py:data:`SECURITY_POST_LOGIN_VIEW`.
651 In this example it will find the ``next=/protected`` in the request.args and redirect to ``/protected``.