Simple security for Flask apps
Flask-Security provides comprehensive authentication functionality including user login/logout, session management, token-based authentication, and integration with Flask-Login. It handles password hashing, user tracking, and authentication token generation.
Core functions for managing user authentication sessions.
def login_user(user, remember=None):
"""
Log in a user and handle tracking if enabled.
Args:
user: User instance to log in
remember (bool, optional): Whether to set remember me cookie
Returns:
bool: True if login successful
"""
def logout_user():
"""
Log out the current user.
Cleans up session and remember cookie, sends identity_changed signal.
Returns:
bool: True if logout successful
"""Flask-Security provides a proxy to access the currently authenticated user.
# Current user proxy - automatically updated on login/logout
current_user: Union[User, AnonymousUser]Utility function for generating URLs to Flask-Security endpoints.
def url_for_security(endpoint, **values):
"""
Generate URLs for security blueprint endpoints.
Args:
endpoint (str): Security endpoint name (e.g., 'login', 'logout')
**values: Additional URL parameters
Returns:
str: Generated URL
"""Functions for password hashing, verification, and security.
def hash_password(password):
"""
Hash a password using the configured password hash.
Args:
password (str): Plain text password
Returns:
str: Hashed password
"""
def verify_password(password, password_hash):
"""
Verify a password against its hash.
Args:
password (str): Plain text password
password_hash (str): Hashed password
Returns:
bool: True if password is correct
"""
def verify_and_update_password(password, user):
"""
Verify password and update hash if using deprecated scheme.
Args:
password (str): Plain text password
user: User instance
Returns:
bool: True if password is correct
"""Functions for generating and validating authentication tokens.
def get_token_status(token, serializer, max_age=None, return_data=False):
"""
Validate token status and extract data.
Args:
token (str): Token to validate
serializer: Serializer instance
max_age (int, optional): Maximum token age in seconds
return_data (bool): Whether to return token data
Returns:
tuple: (expired, invalid, data) status
"""Functions for working with user identity attributes and lookup.
def get_identity_attributes(app=None):
"""
Get configured user identity attributes (usually email).
Args:
app (Flask, optional): Flask application instance
Returns:
list: List of identity attribute names
"""from flask import request, redirect, url_for
from flask_security import login_user, logout_user, current_user
@app.route('/custom_login', methods=['POST'])
def custom_login():
email = request.form.get('email')
password = request.form.get('password')
remember = request.form.get('remember', False)
user = user_datastore.find_user(email=email)
if user and verify_password(password, user.password):
login_user(user, remember=remember)
return redirect(url_for('dashboard'))
return "Invalid credentials", 401
@app.route('/custom_logout')
def custom_logout():
logout_user()
return redirect(url_for('index'))from flask_security import current_user
@app.route('/profile')
def profile():
if current_user.is_authenticated:
return f"Welcome, {current_user.email}!"
else:
return redirect(url_for_security('login'))
@app.template_global()
def is_logged_in():
return current_user.is_authenticatedfrom flask_security import hash_password, verify_password
# Hash password for new user
password_hash = hash_password('user_password')
user = user_datastore.create_user(
email='user@example.com',
password=password_hash
)
# Verify password during login
if verify_password('user_password', user.password):
print("Password is correct")
# Update password with verification
def change_password(user, old_password, new_password):
if verify_password(old_password, user.password):
user.password = hash_password(new_password)
user_datastore.put(user)
user_datastore.commit()
return True
return Falsefrom flask_security import current_user
# Get user's authentication token
@app.route('/api/get-token')
def get_auth_token():
if current_user.is_authenticated:
token = current_user.get_auth_token()
return {'token': token}
return {'error': 'Not authenticated'}, 401
# API endpoint that accepts token authentication
@app.route('/api/data')
def api_data():
# Token authentication is handled automatically by Flask-Security
# if SECURITY_AUTH_TOKEN_REQUIRED is configured
return {'data': 'Protected data'}from flask_security import url_for_security
# Generate security URLs in templates or views
login_url = url_for_security('login')
logout_url = url_for_security('logout')
register_url = url_for_security('register')
# With additional parameters
login_url_with_next = url_for_security('login', next='/dashboard')Flask-Security can track user login information when SECURITY_TRACKABLE is enabled:
from flask_security import current_user
from datetime import datetime
@app.route('/login_info')
def login_info():
if current_user.is_authenticated:
return {
'last_login_at': current_user.last_login_at,
'current_login_at': current_user.current_login_at,
'last_login_ip': current_user.last_login_ip,
'current_login_ip': current_user.current_login_ip,
'login_count': current_user.login_count
}
return {'error': 'Not authenticated'}, 401# Login with remember me
login_user(user, remember=True)
# Check if user was remembered
@app.route('/check_remember')
def check_remember():
# Flask-Login handles remember cookie automatically
if current_user.is_authenticated:
return "User is logged in (possibly remembered)"
return "User not logged in"from flask_security import login_user, current_user
from flask import session
def authenticate_with_custom_method(username, auth_data):
"""Custom authentication method"""
user = user_datastore.find_user(username=username)
if user and custom_verify_auth(user, auth_data):
# Log in the user
login_user(user)
# Store additional session data
session['auth_method'] = 'custom'
session['auth_time'] = datetime.utcnow()
return True
return False
def custom_verify_auth(user, auth_data):
"""Implement your custom authentication logic"""
# Example: API key verification, LDAP, OAuth, etc.
return True # Replace with actual verificationtessl i tessl/pypi-flask-security@3.0.0