Quickly add security features to your Flask application.
npx @tessl/cli install tessl/pypi-flask-security@5.6.0A comprehensive security extension for Flask applications that provides authentication, authorization, registration, password recovery, email confirmation, two-factor authentication, WebAuthn support, and unified signin capabilities. Flask-Security implements OWASP security best practices with a batteries-included approach supporting multiple database backends, internationalization, various password hashing algorithms, session management, role-based access control, and extensive customization options.
pip install Flask-Securityfrom flask_security import SecurityCommon imports for authentication and authorization:
from flask_security import (
Security,
UserMixin,
RoleMixin,
login_required,
roles_required,
current_user
)from flask import Flask
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin, login_required
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
# Define models
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(80), unique=True)
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(255), unique=True)
password = db.Column(db.String(255))
active = db.Column(db.Boolean(), default=True)
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
@app.route('/profile')
@login_required
def profile():
return f'Hello {current_user.email}!'
if __name__ == '__main__':
with app.app_context():
db.create_all()
app.run(debug=True)Flask-Security uses a modular architecture with several key components:
This architecture enables Flask-Security to integrate seamlessly with existing Flask applications while providing comprehensive security features through a unified, consistent API.
Essential classes and functions for initializing Flask-Security in your application, including the main Security extension class and core user/role mixins.
class Security:
def __init__(self, app=None, datastore=None, **kwargs): ...
class UserMixin:
def is_authenticated(self) -> bool: ...
def is_active(self) -> bool: ...
def is_anonymous(self) -> bool: ...
def get_id(self) -> str: ...
class RoleMixin:
def __eq__(self, other) -> bool: ...
def __ne__(self, other) -> bool: ...
def current_user(): ...Authentication decorators, login/logout functions, and session management for controlling access to protected resources.
def login_required(func): ...
def auth_required(*auth_methods): ...
def login_user(user, remember=False, duration=None, force=False, fresh=True): ...
def logout_user(): ...
def verify_password(password: str, password_hash: str) -> bool: ...User registration forms, email confirmation workflow, and account activation functionality.
class RegisterForm(Form): ...
class ConfirmRegisterForm(Form): ...
def register_user(**kwargs): ...
def send_confirmation_instructions(user): ...
def confirm_user(user): ...Password hashing, validation, reset workflows, and security utilities for managing user passwords.
def hash_password(password: str) -> str: ...
class ChangePasswordForm(Form): ...
class ForgotPasswordForm(Form): ...
class ResetPasswordForm(Form): ...
def send_reset_password_instructions(user): ...Authorization decorators, role management, and permission-based access control for implementing fine-grained security policies.
def roles_required(*roles): ...
def roles_accepted(*roles): ...
def permissions_required(*permissions): ...
def permissions_accepted(*permissions): ...TOTP-based two-factor authentication, SMS support, recovery codes, and backup authentication methods.
class TwoFactorSetupForm(Form): ...
class TwoFactorVerifyCodeForm(Form): ...
def tf_send_security_token(user, method): ...
class Totp:
def generate_password(self) -> str: ...
def verify(self, token: str, window: int = 0) -> bool: ...WebAuthn/FIDO2 authentication for passwordless and phishing-resistant authentication using hardware security keys and biometrics.
class WebAuthnRegisterForm(Form): ...
class WebAuthnSigninForm(Form): ...
class WebAuthnMixin:
def webauthn_credentials(self): ...Unified signin interface supporting multiple authentication methods (password, WebAuthn, magic links) through a single form.
class UnifiedSigninForm(Form): ...
class UnifiedVerifyForm(Form): ...
def us_send_security_token(user, method): ...Datastore classes and database abstraction layer supporting multiple ORMs and databases.
class UserDatastore:
def get_user(self, identifier): ...
def create_user(self, **kwargs): ...
def delete_user(self, user): ...
class SQLAlchemyUserDatastore(UserDatastore): ...
class MongoEngineUserDatastore(UserDatastore): ...
class PeeweeUserDatastore(UserDatastore): ...Helper functions for URLs, tokens, validation, and other common security operations.
def url_for_security(endpoint: str, **values) -> str: ...
def get_hmac(password: str) -> str: ...
def send_mail(subject: str, recipient: str, template: str, **context): ...
def lookup_identity(identity: str): ...Flask-Security provides extensive configuration options through Flask's config system. Key configuration variables include:
SECURITY_PASSWORD_SALT: Salt for password hashingSECURITY_LOGIN_URL: Login page URL endpointSECURITY_LOGOUT_URL: Logout URL endpointSECURITY_REGISTERABLE: Enable user registrationSECURITY_RECOVERABLE: Enable password recoverySECURITY_CONFIRMABLE: Enable email confirmationSECURITY_TWO_FACTOR: Enable two-factor authenticationSECURITY_WEBAUTHN: Enable WebAuthn supportFlask-Security raises specific exceptions for various error conditions:
BadSignature: Invalid or tampered tokensSignatureExpired: Expired tokensEmailValidateException: Email validation errorsFlask-Security emits signals for key events that applications can listen to:
user_authenticated: User successfully logged inuser_registered: New user registeredpassword_changed: User changed passwordtf_code_confirmed: Two-factor code verified