CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-security

Quickly add security features to your Flask application.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Flask-Security

A 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.

Package Information

  • Package Name: Flask-Security
  • Language: Python
  • Installation: pip install Flask-Security
  • Version: 5.6.2

Core Imports

from flask_security import Security

Common imports for authentication and authorization:

from flask_security import (
    Security, 
    UserMixin, 
    RoleMixin,
    login_required,
    roles_required,
    current_user
)

Basic Usage

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)

Architecture

Flask-Security uses a modular architecture with several key components:

  • Security Class: Main extension for Flask app initialization and configuration
  • Datastore Layer: Abstracts database operations across different ORMs (SQLAlchemy, MongoEngine, Peewee, Pony)
  • User/Role Mixins: Provide standard methods and properties for user and role models
  • Authentication Layer: Handles login, logout, token management, and session handling
  • Authorization Layer: Manages role-based and permission-based access control
  • Form System: Customizable forms for all security operations (login, registration, password reset, etc.)
  • Signal System: Event hooks for extending functionality (user_authenticated, password_changed, etc.)
  • Feature Modules: Optional components like two-factor auth, WebAuthn, unified signin

This architecture enables Flask-Security to integrate seamlessly with existing Flask applications while providing comprehensive security features through a unified, consistent API.

Capabilities

Core Setup & Configuration

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

Core Setup

User Authentication

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: ...

Authentication

User Registration & Confirmation

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): ...

Registration

Password Management

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): ...

Password Management

Role-Based Access Control

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): ...

Authorization

Two-Factor Authentication

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: ...

Two-Factor Authentication

WebAuthn Support

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): ...

WebAuthn

Unified Signin

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): ...

Unified Signin

Database Integration

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): ...

Database Integration

Utility Functions

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): ...

Utilities

Configuration

Flask-Security provides extensive configuration options through Flask's config system. Key configuration variables include:

  • SECURITY_PASSWORD_SALT: Salt for password hashing
  • SECURITY_LOGIN_URL: Login page URL endpoint
  • SECURITY_LOGOUT_URL: Logout URL endpoint
  • SECURITY_REGISTERABLE: Enable user registration
  • SECURITY_RECOVERABLE: Enable password recovery
  • SECURITY_CONFIRMABLE: Enable email confirmation
  • SECURITY_TWO_FACTOR: Enable two-factor authentication
  • SECURITY_WEBAUTHN: Enable WebAuthn support

Error Handling

Flask-Security raises specific exceptions for various error conditions:

  • BadSignature: Invalid or tampered tokens
  • SignatureExpired: Expired tokens
  • EmailValidateException: Email validation errors

Signals

Flask-Security emits signals for key events that applications can listen to:

  • user_authenticated: User successfully logged in
  • user_registered: New user registered
  • password_changed: User changed password
  • tf_code_confirmed: Two-factor code verified

docs

authentication.md

authorization.md

core-setup.md

database.md

index.md

password-management.md

registration.md

two-factor.md

unified-signin.md

utilities.md

webauthn.md

tile.json