Quickly add security features to your Flask application.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Authentication decorators, login/logout functions, session management, and access control mechanisms for protecting routes and resources in Flask applications.
Decorators for protecting routes and requiring user authentication with various methods and flexibility.
def auth_required(*auth_methods):
"""
Flexible authentication decorator supporting multiple authentication mechanisms.
Parameters:
- auth_methods: Tuple of authentication methods ('session', 'token', 'basic')
If empty, uses configured default methods
Returns:
Decorator function that enforces authentication
"""
def login_required(func):
"""
Decorator requiring user to be logged in via session authentication.
Legacy wrapper around auth_required().
Parameters:
- func: Function to decorate
Returns:
Decorated function that requires login
"""
def auth_token_required(func):
"""
Decorator requiring API token authentication.
Parameters:
- func: Function to decorate
Returns:
Decorated function that requires valid auth token
"""
def http_auth_required(func):
"""
Decorator requiring HTTP basic authentication.
Parameters:
- func: Function to decorate
Returns:
Decorated function that requires HTTP basic auth
"""
def anonymous_user_required(func):
"""
Decorator requiring user to be anonymous (not authenticated).
Parameters:
- func: Function to decorate
Returns:
Decorated function that requires anonymous user
"""Core functions for managing user authentication sessions and login state.
def login_user(user, remember=False, duration=None, force=False, fresh=True):
"""
Log in a user with session management.
Parameters:
- user: User object to log in
- remember: Whether to set remember-me cookie (default: False)
- duration: Duration for remember-me cookie (default: None)
- force: Force login even if user is inactive (default: False)
- fresh: Mark authentication as fresh (default: True)
Returns:
True if login successful, False otherwise
"""
def logout_user():
"""
Log out the current user by clearing session data.
Returns:
True if logout successful, False otherwise
"""Functions for managing authentication freshness requirements for sensitive operations.
def check_and_update_authn_fresh(within, grace=None):
"""
Check if current authentication is fresh and update if needed.
Parameters:
- within: Time period (timedelta) within which auth must be fresh
- grace: Grace period for allowing stale authentication (default: None)
Returns:
Tuple of (is_fresh: bool, is_grace: bool)
"""Functions for verifying user passwords against stored hashes.
def verify_password(password, password_hash):
"""
Verify a password against its hash.
Parameters:
- password: Plain text password to verify
- password_hash: Stored password hash to verify against
Returns:
True if password matches hash, False otherwise
"""
def verify_and_update_password(password, user):
"""
Verify password and update hash if needed (e.g., algorithm upgrade).
Parameters:
- password: Plain text password to verify
- user: User object with password hash
Returns:
True if password matches, False otherwise
"""Functions for finding users by various identity attributes.
def lookup_identity(identity):
"""
Look up user by identity (email, username, or other configured attribute).
Parameters:
- identity: Identity string to search for
Returns:
User object if found, None otherwise
"""Default handler functions for various authentication scenarios that can be customized.
def default_unauthn_handler(mechanisms, headers=None):
"""
Default handler for unauthenticated requests.
Parameters:
- mechanisms: List of available authentication mechanisms
- headers: Additional headers to include in response
Returns:
Flask response for unauthenticated request
"""
def default_reauthn_handler(within, grace):
"""
Default handler for re-authentication requirements.
Parameters:
- within: Required freshness period
- grace: Grace period for stale authentication
Returns:
Flask response for re-authentication request
"""
def default_unauthz_handler():
"""
Default handler for unauthorized access attempts.
Returns:
Flask response for unauthorized request
"""Core form for user login and authentication.
class LoginForm(Form):
"""
User login form with email/username and password fields.
Fields:
- email: Email or username field (identity)
- password: Password field
- remember: Remember me checkbox (optional)
- next: Next URL hidden field
"""
email: StringField
password: PasswordField
remember: BooleanField
next: HiddenField
class VerifyForm(Form):
"""
Password verification form for sensitive operations.
Fields:
- password: Password field for verification
"""
password: PasswordField
class PasswordlessLoginForm(Form):
"""
Passwordless authentication form.
Fields:
- user: Email or username field
"""
user: StringFieldFlask-Security supports multiple authentication mechanisms that can be used individually or in combination:
from flask_security import login_required, auth_required, current_user
@app.route('/profile')
@login_required
def profile():
return f"Hello {current_user.email}!"
@app.route('/api/data')
@auth_required('token')
def api_data():
return {"data": "sensitive information"}
@app.route('/admin')
@auth_required('session', 'token')
def admin():
return "Admin panel"from flask_security import login_user, logout_user, verify_password, lookup_identity
@app.route('/custom-login', methods=['POST'])
def custom_login():
email = request.form.get('email')
password = request.form.get('password')
user = lookup_identity(email)
if user and verify_password(password, user.password):
login_user(user, remember=True)
return redirect('/dashboard')
else:
flash('Invalid credentials')
return redirect('/login')
@app.route('/custom-logout')
def custom_logout():
logout_user()
return redirect('/')from datetime import timedelta
from flask_security import check_and_update_authn_fresh
@app.route('/sensitive-operation')
@login_required
def sensitive_operation():
# Require authentication within last 10 minutes
is_fresh, is_grace = check_and_update_authn_fresh(
within=timedelta(minutes=10)
)
if not is_fresh:
return redirect(url_for_security('verify'))
return "Performing sensitive operation"from flask_security import send_login_instructions
@app.route('/passwordless-login', methods=['POST'])
def passwordless_login():
email = request.form.get('email')
user = lookup_identity(email)
if user:
send_login_instructions(user)
flash('Login instructions sent to your email')
return redirect('/login')