Docsity

Flask-Security Documentation, Study notes of Logic

Partial preview of the text

Download Flask-Security Documentation and more Study notes Logic in PDF only on Docsity!

Flask-Security Documentation

Release 4.1.

Matt Wright

Chris Wagner

Apr 19, 2022

ii

Flask-Security allows you to quickly add common security mechanisms to your Flask application. They include:

  1. Session based authentication
  2. Role and Permission management
  3. Password hashing
  4. Basic HTTP authentication
  5. Token based authentication
  6. Token based account activation (optional)
  7. Token based password recovery / resetting (optional)
  8. Two-factor authentication (optional)
  9. Unified sign in (optional)
  10. User registration (optional)
  11. Login tracking (optional)
  12. JSON/Ajax Support

Many of these features are made possible by integrating various Flask extensions and libraries. They include:

  • Flask-Login
  • Flask-Mail
  • Flask-Principal
  • Flask-WTF
  • itsdangerous
  • passlib
  • PyQRCode

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:

  1. Flask-SQLAlchemy
  2. Flask-MongoEngine
  3. Peewee Flask utils
  4. PonyORM - NOTE: not currently supported.
  5. SQLAlchemy sessions

CONTENTS 1

CHAPTER

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:

  • Flask
  • Flask-Login
  • Flask-Principal
  • Flask-WTF
  • email-validator
  • itsdangerous
  • passlib
  • Blinker

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:

  • babel - Translation services. It will install babel and Flask-Babel.
  • fsqla - Use flask-sqlalchemy and sqlalchemy as your storage interface.
  • common - Install Flask-Mail, and bcrypt (the default password hash).
  • mfa - Install packages used for multi-factor (two-factor and unified signin): cryptography, pyqrcode, phonenum- berslite (note that for SMS you still need to pick an SMS provider and install appropriate packages).

Your application will also need a database backend:

  • Sqlite is supported out of the box.
  • For PostgreSQL install psycopg2.
  • For MySQL install pymysql.
  • For MongoDB install Flask-Mongoengine.

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.

  • Basic SQLAlchemy Application
  • Basic SQLAlchemy Application with session
  • Basic MongoEngine Application
  • Basic Peewee Application
  • Mail Configuration
  • Proxy Configuration
  • Unit Testing Your Application

1.2.1 Basic SQLAlchemy Application

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()

Views

@app.route("/") @auth_required() def home(): return render_template_string("Hello {{ current_user.email }}")

if name == 'main': app.run()

1.2.2 Basic SQLAlchemy Application with session

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.

  • app.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

Create app

app = Flask(name) app.config['DEBUG'] = True

Generate a nice key using secrets.token_urlsafe()

app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy- ˓→cQkeDPhv9Cb3Ag-wyJILbq_dFw')

Bcrypt is set as default SECURITY_PASSWORD_HASH, which requires a salt

Generate a good salt using: secrets.SystemRandom().getrandbits(128)

(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 ')

Setup Flask-Security

user_datastore = SQLAlchemySessionUserDatastore(db_session, User, Role) security = Security(app, user_datastore)

Create a user to test with

@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()

Views

@app.route("/") @auth_required() def home(): return render_template_string('Hello {{email}} !', email=current_user.email)

if name == 'main': app.run()

  • database.py

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 all modules here that might define models so that

they will be registered properly on the metadata. Otherwise

you will have to import them first before calling init_db()

import models Base.metadata.create_all(bind=engine)

  • models.py

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)

Create app

app = Flask(name) app.config['DEBUG'] = True

Generate a nice key using secrets.token_urlsafe()

app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag- ˓→wyJILbq_dFw')

Bcrypt is set as default SECURITY_PASSWORD_HASH, which requires a salt

Generate a good salt using: secrets.SystemRandom().getrandbits(128)

app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", ˓→' 146585145368132386173505678016728509634 ')

MongoDB Config

app.config['MONGODB_DB'] = 'mydatabase' app.config['MONGODB_HOST'] = 'localhost' app.config['MONGODB_PORT'] = 27017

Create database connection object

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=[])

Setup Flask-Security

user_datastore = MongoEngineUserDatastore(db, User, Role) security = Security(app, user_datastore)

Create a user to test with

@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 ˓→"))

Views

@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()

1.2.4 Basic Peewee Application

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

Create app

app = Flask(name) app.config['DEBUG'] = True

Generate a nice key using secrets.token_urlsafe()

app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY", 'pf9Wkove4IKEAXvy-cQkeDPhv9Cb3Ag- ˓→wyJILbq_dFw')

Bcrypt is set as default SECURITY_PASSWORD_HASH, which requires a salt

Generate a good salt using: secrets.SystemRandom().getrandbits(128)

app.config['SECURITY_PASSWORD_SALT'] = os.environ.get("SECURITY_PASSWORD_SALT", ˓→' 146585145368132386173505678016728509634 ')

app.config['DATABASE'] = { 'name': 'example.db', 'engine': 'peewee.SqliteDatabase', }

Create database connection object

db = FlaskDB(app)

class Role(RoleMixin, db.Model): name = CharField(unique=True) description = TextField(null=True) permissions = TextField(null=True)

N.B. order is important since db.Model also contains a get_id() -

we need the one from UserMixin.

(continues on next page)

10 Chapter 1. Getting Started

1.2.5 Mail Configuration

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:

At top of file

from flask_mail import Mail

After 'Create app'

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.

1.2.6 Proxy Configuration

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:

At top of file

from werkzeug.middleware.proxy_fix import ProxyFix

After 'Create app'

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)

To learn more about the ProxyFix middleware, please see the Werkzeug documentation.

1.2.7 Unit Testing Your Application

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:

  • ‘Pure’ unit test - mocking out all lower level objects (such as the data store)
  • Complete app with in-memory/temporary DB (with little or no mocking).

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

Our test emails/domain isn't necessarily valid

app.config["SECURITY_EMAIL_VALIDATOR_ARGS"] = {"check_deliverability": False}

Make this plaintext for most tests - reduces unit test time by 50%

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:

1.3.1 Session Based Authentication

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.

1.3.2 Role/Identity Based Access

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.

1.3.3 Password Hashing

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.

1.3.4 Password Validation and Complexity

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 :

  • Change password does not work if a user registers without a password. However forgot-password will allow the user to set a new password.
  • Registration and Confirmation only work with email - so while you can enable multiple authentication methods, you still have to register with email.

1.3.9 Email Confirmation

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.

1.3.10 Password Reset/Recovery

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.

1.3.11 User Registration

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

1.3.12 Password Change

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.

1.3.13 Login Tracking

Flask-Security can, if configured, keep track of basic login events and statistics. They include:

  • Last login date
  • Current login date
  • Last login IP address
  • Current login IP address
  • Total login count

1.3.14 JSON/Ajax Support

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:

  • Login requests
  • Unified sign in requests
  • Registration requests
  • Change password requests
  • Confirmation requests
  • Forgot password requests
  • Passwordless login requests
  • Two-factor login requests
  • Change two-factor method requests

In addition, Single-Page-Applications (like those built with Vue, Angular, and React) are supported via customizable redirect links.

16 Chapter 1. Getting Started