




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































ii
Flask-Security allows you to quickly add common security mechanisms to your Flask application. They include:
Many of these features are made possible by integrating various Flask extensions and libraries. They include:
Additionally, it assumes you’ll be using a common library for your database connections and model definitions. Flask- Security supports the following Flask extensions out of the box for data persistence:
ONE
GETTING STARTED
1.1 Installation
Installing Flask-Security-Too using:
pip install flask-security-too
will install the basic package along with its required dependencies:
These are not sufficient for a complete application - other packages are required based on features desired, password hash algorithms, storage backend, etc. Flask-Security-Too has additional distribution ‘extras’ that can reduce the hassle of figuring out all the required packages. You can install these using the standard pip syntax:
pip install flask-security-too[extra1,extra2, ...]
Supported extras are:
Your application will also need a database backend:
For additional details on configuring your database engine connector - refer to sqlalchemy_engine
1.2 Quick Start
There are some complete (but simple) examples available in the examples directory of the Flask-Security repo.
Note: The below quickstarts are just that - they don’t enable most of the features (such as registration, reset, etc.). They basically create a single user, and you can login as that user... that’s it. As you add more features, additional packages (e.g. Flask-Mail, Flask-Babel, pyqrcode) might be required and will need to be added to your requirements.txt (or equivalent) file. Flask-Security does some configuration validation and will output error messages to the console for some missing packages.
Note: The default SECURITY_PASSWORD_HASH is “bcrypt” - so be sure to install bcrypt. If you opt for a different hash e.g. “argon2” you will need to install e.g. argon_cffi.
Danger: The examples below place secrets in source files. Never do this for your application especially if your source code is placed in a public repo. How you pass in secrets securely will depend on your deployment model - however in most cases (e.g. docker, lambda) using environment variables will be the easiest.
SQLAlchemy Install requirements
$ python3 -m venv pymyenv $. pymyenv/bin/activate $ pip install flask-security-too[fsqla,common]
4 Chapter 1. Getting Started
(continued from previous page)
@app.before_first_request def create_user(): db.create_all() if not user_datastore.find_user(email="[email protected]"): user_datastore.create_user(email="[email protected]", password=hash_password("password ˓→")) db.session.commit()
@app.route("/") @auth_required() def home(): return render_template_string("Hello {{ current_user.email }}")
if name == 'main': app.run()
SQLAlchemy Install requirements
$ python3 -m venv pymyenv $. pymyenv/bin/activate $ pip install flask-security-too[common] sqlalchemy
SQLAlchemy Application
The following code sample illustrates how to get started as quickly as possible using SQLAlchemy in a declarative way:
This example shows how to split your application into 3 files: app.py, database.py and models.py.
import os
from flask import Flask, render_template_string from flask_security import Security, current_user, auth_required, hash_password, SQLAlchemySessionUserDatastore from database import db_session, init_db from models import User, Role
app = Flask(name) app.config['DEBUG'] = True
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy- ˓→cQkeDPhv9Cb3Ag-wyJILbq_dFw')
(continues on next page)
6 Chapter 1. Getting Started
(continued from previous page) app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", ˓→' 146585145368132386173505678016728509634 ')
user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role) security = Security(app, user_datastore)
@app.before_first_request def create_user(): init_db() if not user_datastore.find_user(email="[email protected]"): user_datastore.create_user(email="[email protected]", password=hash_password( ˓→"password")) db_session.commit()
@app.route("/") @auth_required() def home(): return render_template_string('Hello {{email}} !', email=current_user.email)
if name == 'main': app.run()
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:////tmp/test.db') db_session = scoped_session(sessionmaker(autocommit=False, autoflush=False, bind=engine)) Base = declarative_base() Base.query = db_session.query_property()
def init_db():
import models Base.metadata.create_all(bind=engine)
from database import Base from flask_security import UserMixin, RoleMixin from sqlalchemy import create_engine from sqlalchemy.orm import relationship, backref from sqlalchemy import Boolean, DateTime, Column, Integer, (continues on next page)
1.2. Quick Start 7
(continued from previous page)
app = Flask(name) app.config['DEBUG'] = True
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag- ˓→wyJILbq_dFw')
app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", ˓→' 146585145368132386173505678016728509634 ')
app.config['MONGODB_DB'] = 'mydatabase' app.config['MONGODB_HOST'] = 'localhost' app.config['MONGODB_PORT'] = 27017
db = MongoEngine(app)
class Role(db.Document, RoleMixin): name = db.StringField(max_length=80, unique=True) description = db.StringField(max_length=255) permissions = db.StringField(max_length=255)
class User(db.Document, UserMixin): email = db.StringField(max_length=255, unique=True) password = db.StringField(max_length=255) active = db.BooleanField(default=True) fs_uniquifier = db.StringField(max_length=64, unique=True) confirmed_at = db.DateTimeField() roles = db.ListField(db.ReferenceField(Role), default=[])
user_datastore = MongoEngineUserDatastore(db, User, Role) security = Security(app, user_datastore)
@app.before_first_request def create_user(): if not user_datastore.find_user(email="[email protected]"): user_datastore.create_user(email="[email protected]", password=hash_password("password ˓→"))
@app.route("/") @auth_required() def home(): return render_template_string("Hello {{ current_user.email }}")
if name == 'main': (continues on next page)
1.2. Quick Start 9
(continued from previous page) app.run()
Peewee Install requirements
$ python3 -m venv pymyenv $. pymyenv/bin/activate $ pip install flask-security-too peewee bcrypt
Peewee Application
The following code sample illustrates how to get started as quickly as possible using Peewee:
import os
from flask import Flask, render_template from playhouse.flask_utils import FlaskDB from peewee import * from flask_security import Security, PeeweeUserDatastore, UserMixin, RoleMixin, auth_required, hash_password
app = Flask(name) app.config['DEBUG'] = True
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag- ˓→wyJILbq_dFw')
app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", ˓→' 146585145368132386173505678016728509634 ')
app.config['DATABASE'] = { 'name': 'example.db', 'engine': 'peewee.SqliteDatabase', }
db = FlaskDB(app)
class Role(RoleMixin, db.Model): name = CharField(unique=True) description = TextField(null=True) permissions = TextField(null=True)
(continues on next page)
10 Chapter 1. Getting Started
Flask-Security integrates with an outgoing mail service via the mail_util_cls which is part of initial configuration. The default class flask_security.MailUtil utilizes the Flask-Mail package. Be sure to add flask_mail to your requirements.txt.
The following code illustrates a basic setup, which could be added to the basic application code in the previous section:
from flask_mail import Mail
app.config['MAIL_SERVER'] = 'smtp.example.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USE_SSL'] = False app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = 'username' app.config['MAIL_PASSWORD'] = 'password' mail = Mail(app)
To learn more about the various Flask-Mail settings to configure it to work with your particular email server configu- ration, please see the Flask-Mail documentation.
The user tracking features need an additional configuration in HTTP proxy environment. The following code illustrates a setup with a single HTTP proxy in front of the web application:
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
To learn more about the ProxyFix middleware, please see the Werkzeug documentation.
As soon as you add any of the Flask-Security decorators to your API endpoints, it can be frustrating to unit test your basic routing (and roles and permissions). Without getting into the argument of the difference between unit tests and integration tests - you can approach testing in 2 ways:
Look in the Flask-Security repo examples directory for actual code that implements the first approach.
You also might want to set the following configurations in your conftest.py:
app.config["WTF_CSRF_ENABLED"] = False
app.config["SECURITY_EMAIL_VALIDATOR_ARGS"] = {"check_deliverability": False}
app.config["SECURITY_PASSWORD_HASH"] = "plaintext"
12 Chapter 1. Getting Started
1.3 Features
Flask-Security allows you to quickly add common security mechanisms to your Flask application. They include:
Session based authentication is fulfilled entirely by the Flask-Login extension. Flask-Security handles the configuration of Flask-Login automatically based on a few of its own configuration values and uses Flask-Login’s alternative token feature to associate the value of fs_uniquifier with the user. (This enables easily invalidating all existing sessions for a given user without having to change their user id). Flask-WTF integrates with the session as well to provide out of the box CSRF support. Flask-Security extends that to support configurations that would require CSRF for requests that are authenticated via session cookies, but not for requests authenticated using tokens.
Flask-Security implements very basic role management out of the box. This means that you can associate a high level role or multiple roles to any user. For instance, you may assign roles such as Admin , Editor , SuperUser , or a combination of said roles to a user. Access control is based on the role name and/or permissions contained within the role; and all roles should be uniquely named. This feature is implemented using the Flask-Principal extension. As with basic RBAC, permissions can be assigned to roles to provide more granular access control. Permissions can be associated with one or more roles (the RoleModel contains a list of permissions). The values of permissions are completely up to the developer - Flask-Security simply treats them as strings. If you’d like to implement even more granular access control (such as per-object), you can refer to the Flask-Principal documentation on this topic.
Password hashing is enabled with passlib. Passwords are hashed with the bcrypt function by default but you can easily configure the hashing algorithm. You should always use a hashing algorithm in your production environment. Hash algorithms not listed in SECURITY_PASSWORD_SINGLE_HASH will be double hashed - first an HMAC will be computed, then the selected hash function will be used. In this case - you must provide a SECURITY_PASSWORD_SALT. A good way to generate this is:
secrets.SystemRandom().getrandbits(128)
Bear in mind passlib does not assume which algorithm you will choose and may require additional libraries to be installed.
Consult Password Validation and Complexity.
1.3. Features 13
Using SMS or an authenticator app means you are providing “something you have” (the mobile device) and either “something you know” (passcode to unlock your device) or “something you are” (biometric quality to unlock your device). This effectively means that using a one-time code to sign in, is in fact already two-factor (if using SMS or authenticator app). Many large authentication providers already offer this - here is Microsoft’s version.
Note that by configuring SECURITY_US_ENABLED_METHODS an application can use this endpoint JUST with iden- tity/password or in fact disallow passwords altogether.
Unified sign in is integrated with two-factor authentication. Since in general there is no need for a second factor if the initial authentication was with SMS or an authenticator application, the SECURITY_US_MFA_REQUIRED configu- ration determines which primary authentication mechanisms require a second factor. By default limited to email and password (if two-factor is enabled).
Be aware that by default, the SECURITY_US_SETUP_URL endpoint is protected with a freshness check (see flask_security.auth_required()) which means it requires a session cookie to function properly. This is true even if using JSON payload or token authentication. If you disable the freshness check then sessions aren’t required.
Current Limited Functionality :
If desired you can require that new users confirm their email address. Flask-Security will send an email message to any new users with a confirmation link. Upon navigating to the confirmation link, the user will be automatically logged in. There is also view for resending a confirmation link to a given email if the user happens to try to use an expired token or has lost the previous email. Confirmation links can be configured to expire after a specified amount of time.
Password reset and recovery is available for when a user forgets their password. Flask-Security sends an email to the user with a link to a view which allows them to reset their password. Once the password is reset they are automatically logged in and can use the new password from then on. Password reset links can be configured to expire after a specified amount of time.
As with password change - this will update the the user’s fs_uniquifier attribute which will invalidate all existing sessions AND (by default) all authentication tokens.
Flask-Security comes packaged with a basic user registration view. This view is very simple and new users need only supply an email address and their password. This view can be overridden if your registration process requires more fields. User email is validated and normalized using the email_validator package.
The SECURITY_USERNAME_ENABLE configuration option, when set to True, will add support for the user to register a username in addition to an email. By default, the user will be able to authenticate with EITHER email or username - however that can be changed via the SECURITY_USER_IDENTITY_ATTRIBUTES.
1.3. Features 15
Flask-Security comes packaged with a basic change user password view. Unlike password recovery, this endpoint is used when the user is already authenticated. The result of a successful password change is not only a new password, but a new value for fs_uniquifier. This has the effect is immediately invalidating all existing sessions. The change request itself effectively re-logs in the user so a new session is created. Note that since the user is effectively re-logged in, the same signals are sent as when the user normally authenticates.
NOTE : The fs_uniquifier by default, controls both sessions and authenticated tokens. Thus changing the password also invalidates all authentication tokens. This may not be desirable behavior, so if the UserModel contains an attribute fs_token_uniquifier, then that will be used when generating authentication tokens and so won’t be affected by password changes.
Flask-Security can, if configured, keep track of basic login events and statistics. They include:
Flask-Security supports JSON/Ajax requests where appropriate. Please look at CSRF for details on how to work with JSON and Single Page Applications. More specifically JSON is supported for the following operations:
In addition, Single-Page-Applications (like those built with Vue, Angular, and React) are supported via customizable redirect links.
16 Chapter 1. Getting Started