| 1 |
Two-factor Configurations |
| 2 |
========================= |
| 3 |
|
| 4 |
Two-factor authentication provides a second layer of security to any type of |
| 5 |
login, requiring extra information or a secondary device to log in, in addition |
| 6 |
to ones login credentials. The added feature includes the ability to add a |
| 7 |
secondary authentication method using either an email link, sms message, or an |
| 8 |
Authenticator app such as Google, Lastpass, or Authy. |
| 9 |
|
| 10 |
The following code sample illustrates how to get started as quickly as |
| 11 |
possible using SQLAlchemy and two-factor feature. In this example both |
| 12 |
email and an authenticator app is supported as a second factor. See below |
| 13 |
for information about SMS. |
| 14 |
|
| 15 |
Basic SQLAlchemy Two-Factor Application |
| 16 |
+++++++++++++++++++++++++++++++++++++++ |
| 17 |
|
| 18 |
SQLAlchemy Install requirements |
| 19 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 20 |
|
| 21 |
:: |
| 22 |
|
| 23 |
$ python3 -m venv pymyenv |
| 24 |
$ . pymyenv/bin/activate |
| 25 |
$ pip install flask-security[common,mfa,fsqla] |
| 26 |
|
| 27 |
|
| 28 |
Two-factor Application |
| 29 |
~~~~~~~~~~~~~~~~~~~~~~ |
| 30 |
|
| 31 |
The following code sample illustrates how to get started as quickly as |
| 32 |
possible using SQLAlchemy: |
| 33 |
|
| 34 |
.. code-block:: python |
| 35 |
|
| 36 |
import os |
| 37 |
from flask import Flask, current_app, render_template_string |
| 38 |
from flask_sqlalchemy import SQLAlchemy |
| 39 |
from flask_security import Security, SQLAlchemyUserDatastore, \ |
| 40 |
UserMixin, RoleMixin, auth_required |
| 41 |
from flask_mail import Mail |
| 42 |
|
| 43 |
# Create app |
| 44 |
app = Flask(__name__) |
| 45 |
app.config['DEBUG'] = True |
| 46 |
# Generate a nice key using secrets.token_urlsafe() |
| 47 |
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag-wyJILbq_dFw') |
| 48 |
# Generate a good salt for password hashing using: secrets.SystemRandom().getrandbits(128) |
| 49 |
app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", '146585145368132386173505678016728509634') |
| 50 |
|
| 51 |
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' |
| 52 |
|
| 53 |
app.config['SECURITY_TWO_FACTOR_ENABLED_METHODS'] = ['email', |
| 54 |
'authenticator'] # 'sms' also valid but requires an sms provider |
| 55 |
app.config['SECURITY_TWO_FACTOR'] = True |
| 56 |
app.config['SECURITY_TWO_FACTOR_RESCUE_MAIL'] = "[email protected]" |
| 57 |
|
| 58 |
app.config['SECURITY_TWO_FACTOR_ALWAYS_VALIDATE'] = False |
| 59 |
app.config['SECURITY_TWO_FACTOR_LOGIN_VALIDITY'] = "1 week" |
| 60 |
|
| 61 |
# Generate a good totp secret using: passlib.totp.generate_secret() |
| 62 |
app.config['SECURITY_TOTP_SECRETS'] = {"1": "TjQ9Qa31VOrfEzuPy4VHQWPCTmRzCnFzMKLxXYiZu9B"} |
| 63 |
app.config['SECURITY_TOTP_ISSUER'] = "put_your_app_name" |
| 64 |
|
| 65 |
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = { |
| 66 |
"pool_pre_ping": True, |
| 67 |
} |
| 68 |
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False |
| 69 |
|
| 70 |
# Create database connection object |
| 71 |
db = SQLAlchemy(app) |
| 72 |
|
| 73 |
# Define models |
| 74 |
roles_users = db.Table('roles_users', |
| 75 |
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')), |
| 76 |
db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))) |
| 77 |
|
| 78 |
class Role(db.Model, RoleMixin): |
| 79 |
id = db.Column(db.Integer(), primary_key=True) |
| 80 |
name = db.Column(db.String(80), unique=True) |
| 81 |
description = db.Column(db.String(255)) |
| 82 |
|
| 83 |
class User(db.Model, UserMixin): |
| 84 |
id = db.Column(db.Integer, primary_key=True) |
| 85 |
email = db.Column(db.String(255), unique=True) |
| 86 |
# Make username unique but not required. |
| 87 |
username = db.Column(db.String(255), unique=True, nullable=True) |
| 88 |
password = db.Column(db.String(255)) |
| 89 |
active = db.Column(db.Boolean()) |
| 90 |
fs_uniquifier = db.Column(db.String(255), unique=True, nullable=False) |
| 91 |
confirmed_at = db.Column(db.DateTime()) |
| 92 |
roles = db.relationship('Role', secondary=roles_users, |
| 93 |
backref=db.backref('users', lazy='dynamic')) |
| 94 |
tf_phone_number = db.Column(db.String(128), nullable=True) |
| 95 |
tf_primary_method = db.Column(db.String(64), nullable=True) |
| 96 |
tf_totp_secret = db.Column(db.String(255), nullable=True) |
| 97 |
|
| 98 |
# Setup Flask-Security |
| 99 |
user_datastore = SQLAlchemyUserDatastore(db, User, Role) |
| 100 |
security = Security(app, user_datastore) |
| 101 |
|
| 102 |
mail = Mail(app) |
| 103 |
|
| 104 |
# Views |
| 105 |
@app.route('/') |
| 106 |
@auth_required() |
| 107 |
def home(): |
| 108 |
return render_template_string("Hello {{ current_user.email }}") |
| 109 |
|
| 110 |
# one time setup |
| 111 |
with app.app_context(): |
| 112 |
# Create a user to test with |
| 113 |
db.create_all() |
| 114 |
if not security.datastore.find_user(email='[email protected]'): |
| 115 |
security.datastore.create_user(email='[email protected]', password='password') |
| 116 |
db.session.commit() |
| 117 |
|
| 118 |
if __name__ == '__main__': |
| 119 |
app.run() |
| 120 |
|
| 121 |
Adding SMS |
| 122 |
++++++++++ |
| 123 |
|
| 124 |
Using SMS as a second factor requires access to an SMS service provider such as "Twilio". |
| 125 |
Flask-Security supports Twilio out of the box. |
| 126 |
For other sms service providers you will need to subclass :class:`.SmsSenderBaseClass` and register it: |
| 127 |
|
| 128 |
.. code-block:: python |
| 129 |
|
| 130 |
SmsSenderFactory.senders[<service-name>] = <service-class> |
| 131 |
|
| 132 |
You need to install additional packages:: |
| 133 |
|
| 134 |
pip install phonenumberslite twilio |
| 135 |
|
| 136 |
And set additional configuration variables: |
| 137 |
|
| 138 |
.. code-block:: python |
| 139 |
|
| 140 |
app.config["SECURITY_TWO_FACTOR_ENABLED_METHODS"] = ['email', |
| 141 |
'authenticator', 'sms'] |
| 142 |
app.config["SECURITY_SMS_SERVICE"] = "Twilio" |
| 143 |
app.config["SECURITY_SMS_SERVICE_CONFIG" = |
| 144 |
{'ACCOUNT_SID': <from twilio>, 'AUTH_TOKEN': <from twilio>, 'PHONE_NUMBER': <from twilio>} |
| 145 |
|
| 146 |
.. _2fa_theory_of_operation: |
| 147 |
|
| 148 |
Theory of Operation |
| 149 |
+++++++++++++++++++++ |
| 150 |
|
| 151 |
.. note:: |
| 152 |
Confirming a code as part of user authentication requires that session cookies be received and sent as part of the API. |
| 153 |
This is true regardless of whether the application uses forms or JSON. |
| 154 |
The ``/tf-setup`` endpoint requires freshness information which (as of 5.5.0) is available from the authentication token |
| 155 |
(as well as the session) - so changing a user's 2FA method can be done without cookies. |
| 156 |
|
| 157 |
The Two-factor (2FA) API has four paths: |
| 158 |
|
| 159 |
- Normal login once everything set up |
| 160 |
- Changing 2FA setup |
| 161 |
- Initial login/registration when 2FA is required |
| 162 |
- Rescue |
| 163 |
|
| 164 |
When using forms, the flow from one state to the next is handled by the forms themselves. When using JSON |
| 165 |
the application must explicitly access the appropriate endpoints. The descriptions below is for the JSON access pattern. |
| 166 |
|
| 167 |
Normal Login |
| 168 |
~~~~~~~~~~~~ |
| 169 |
In the normal case, when the user has already setup their preferred 2FA method (e.g. email, SMS, authenticator app), |
| 170 |
then the flow starts with the authentication process using the ``/login`` or ``/us-signin`` endpoints, providing |
| 171 |
their identity and password. If 2FA is required, the response will indicate that. Then, the application must POST to the ``/tf-validate`` |
| 172 |
with the correct code. |
| 173 |
|
| 174 |
Changing 2FA Setup |
| 175 |
~~~~~~~~~~~~~~~~~~~ |
| 176 |
An authenticated user can change their 2FA configuration (primary_method, phone number, etc.). In order to prevent a user from being |
| 177 |
locked out, the new configuration must be validated before it is stored permanently. The user starts with a GET on ``/tf-setup``. This will return |
| 178 |
a list of configured 2FA methods the user can choose from, and the existing configuration. This must be followed with a POST on ``/tf-setup`` with the new primary |
| 179 |
method (and phone number if SMS). In the case of SMS or email, a code will be sent. In addition, a state_token will be returned in the response to |
| 180 |
the POST - this should be used to POST the code to ``/tf-setup/<state_token>``. |
| 181 |
In the case of setting up an authenticator app, the response to the POST will contain the QRcode image as well |
| 182 |
as the required information for manual entry. |
| 183 |
Once the code has been successfully entered, the new configuration will be permanently stored. |
| 184 |
|
| 185 |
Initial login/registration |
| 186 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 187 |
This is basically a combination of the above two - initial POST to ``/login`` will return indicating that 2FA is required. The user must then POST to ``/tf-setup`` to setup |
| 188 |
the desired 2FA method, and finally have the user enter the code and POST to ``/tf-validate``. |
| 189 |
|
| 190 |
Rescue |
| 191 |
~~~~~~ |
| 192 |
Life happens - if the user doesn't have their mobile devices (SMS) or authenticator app, then they can use the ``/tf-rescue`` endpoint to |
| 193 |
see possible recovery options. Flask-Security supports the following: |
| 194 |
|
| 195 |
- Have a one-time code sent to their email (if :py:data:`SECURITY_TWO_FACTOR_RESCUE_EMAIL` is set to ``True``). |
| 196 |
- Send an email to the application administrators. |
| 197 |
- Use a previously setup one-time recovery code (see :py:data:`SECURITY_MULTI_FACTOR_RECOVERY_CODES`) |
| 198 |
|
| 199 |
Validity |
| 200 |
++++++++ |
| 201 |
Sometimes it can be preferable to enter the 2FA code once a day/week/month, especially if a user logs in and out of a website multiple times. This allows the |
| 202 |
security of a two factor authentication but with a slightly better user experience. This can be achieved by setting :py:data:`SECURITY_TWO_FACTOR_ALWAYS_VALIDATE` to ``False``, |
| 203 |
and clicking the 'Remember' button on the login form. Once the two factor code is validated, a cookie is set to allow skipping the validation step. The cookie is named |
| 204 |
``tf_validity`` and contains the signed token containing the user's ``fs_uniquifier``. The cookie and token are both set to expire after the time delta given in |
| 205 |
:py:data:`SECURITY_TWO_FACTOR_LOGIN_VALIDITY`. Note that setting ``SECURITY_TWO_FACTOR_LOGIN_VALIDITY`` to 0 is equivalent to ``SECURITY_TWO_FACTOR_ALWAYS_VALIDATE`` being ``True``. |
| 206 |
|
| 207 |
Fine-Grained Control of Two-Factor |
| 208 |
+++++++++++++++++++++++++++++++++++ |
| 209 |
The decision whether to require a second factor after primary authentication is made in :py:meth:`.UserMixin.check_tf_required`. |
| 210 |
The default implementation returns True if :py:data:`SECURITY_TWO_FACTOR_REQUIRED` is set OR the user has a two-factor method already setup AND |
| 211 |
recent two-factor authentication isn't 'valid' (see above). |
| 212 |
|
| 213 |
This method can be overridden in the application's User class. A common use case might be to require two-factor for any user with the 'admin' role. |