Simple security for Flask apps
Flask-Security is a comprehensive Flask extension that provides authentication and authorization functionality for Flask web applications. It integrates seamlessly with Flask-Login for session management, Flask-Principal for role-based access control, Flask-WTF for secure forms, and passlib for password hashing. The library offers complete user management features including user registration, login/logout, password recovery, email confirmation, role-based permissions, and token-based authentication.
pip install Flask-Securityfrom flask_security import SecurityCommon imports for user and role management:
from flask_security import (
Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin,
login_required, roles_required, login_user, logout_user
)from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_security import Security, SQLAlchemyUserDatastore, UserMixin, RoleMixin
app = Flask(__name__)
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
# Define models
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)
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)
roles = db.relationship('Role', secondary=roles_users, backref='users')
# Setup Flask-Security
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
security = Security(app, user_datastore)
# Create database tables
with app.app_context():
db.create_all()
if not user_datastore.find_user(email="admin@example.com"):
user_datastore.create_user(email="admin@example.com", password="password")
db.session.commit()Flask-Security is built around several key components:
The main Security extension class and configuration system that initializes Flask-Security with your Flask application and manages all security features.
class Security:
def __init__(self, app=None, datastore=None, **kwargs): ...
def init_app(self, app, datastore=None, register_blueprint=True, **kwargs): ...Core classes and mixins for implementing user and role models compatible with Flask-Security's authentication and authorization system.
class UserMixin:
def has_role(self, role): ...
def get_auth_token(self): ...
@property
def is_active(self): ...
class RoleMixin:
def __eq__(self, other): ...
def __ne__(self, other): ...
class AnonymousUser:
def has_role(self, *args): ...Datastore classes that provide an abstraction layer for user and role persistence across different database backends and ORMs.
class SQLAlchemyUserDatastore:
def __init__(self, db, user_model, role_model): ...
def get_user(self, identifier): ...
def find_user(self, **kwargs): ...
def create_user(self, **kwargs): ...
class MongoEngineUserDatastore: ...
class PeeweeUserDatastore: ...
class PonyUserDatastore: ...Functions and utilities for managing user authentication, login/logout operations, and session handling.
def login_user(user, remember=None): ...
def logout_user(): ...
def url_for_security(endpoint, **values): ...
# Current user proxy
current_user: UserDecorators and utilities for implementing role-based access control and protecting views with authentication requirements.
def login_required(fn): ...
def roles_required(*roles): ...
def roles_accepted(*roles): ...
def auth_token_required(fn): ...
def http_auth_required(realm): ...
def auth_required(*auth_methods): ...Form classes for handling user registration, login, password reset, and other security-related user interactions.
class LoginForm: ...
class RegisterForm: ...
class ConfirmRegisterForm: ...
class ForgotPasswordForm: ...
class ResetPasswordForm: ...
class PasswordlessLoginForm: ...Signal objects that allow you to hook into Flask-Security's workflows for customization and extension.
user_registered: Signal
user_confirmed: Signal
confirm_instructions_sent: Signal
password_reset: Signal
reset_password_instructions_sent: SignalOptional security features including email confirmation, password recovery, user registration, password changing, and passwordless authentication.
# Confirmable
def send_confirmation_instructions(user): ...
def confirm_user(user): ...
# Recoverable
def send_reset_password_instructions(user): ...
def update_password(user, password): ...
# Registerable
def register_user(**kwargs): ...class User:
"""Base user interface expected by Flask-Security"""
id: Any
email: str
password: str
active: bool
roles: List[Role]
class Role:
"""Base role interface expected by Flask-Security"""
name: strtessl i tessl/pypi-flask-security@3.0.0