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