CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-flask-httpauth

Simple extension that provides Basic and Digest HTTP authentication for Flask routes

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

basic-auth.mddocs/

Basic Authentication

HTTP Basic authentication implementation providing username/password authentication with secure password verification and hashing support. Basic auth transmits credentials in Base64-encoded format and is suitable for HTTPS environments.

Capabilities

HTTPBasicAuth Class

Creates an HTTP Basic authentication handler with customizable verification callbacks and password hashing support.

class HTTPBasicAuth(HTTPAuth):
    def __init__(self, scheme=None, realm=None):
        """
        Initialize Basic authentication handler.
        
        Parameters:
        - scheme (str, optional): Authentication scheme, defaults to 'Basic'
        - realm (str, optional): Authentication realm, defaults to 'Authentication Required'
        """

Password Verification

Register callback functions for password verification, supporting both plain password and hashed password workflows.

def verify_password(self, f):
    """
    Decorator to register password verification callback.
    
    Parameters:
    - f (function): Callback function(username, password) -> user_object or None
    
    Returns:
    The decorated function
    
    Usage:
    @auth.verify_password
    def verify_password(username, password):
        # Verify credentials and return user object if valid
        return user if valid else None
    """

def hash_password(self, f):
    """
    Decorator to register password hashing callback.
    
    Parameters:
    - f (function): Callback function(password) -> hashed_password or function(username, password) -> hashed_password
    
    Returns:
    The decorated function
    
    Usage:
    @auth.hash_password
    def hash_password(password):
        return generate_password_hash(password)
    """

Route Protection

Protect Flask routes with Basic authentication using the login_required decorator.

def login_required(self, f=None, role=None, optional=None):
    """
    Decorator to require authentication for Flask routes.
    
    Parameters:
    - f (function, optional): Flask route function to protect
    - role (str|list, optional): Required user role(s)
    - optional (bool, optional): Make authentication optional
    
    Returns:
    Decorated function or decorator
    
    Usage:
    @auth.login_required
    def protected_route():
        return f"Hello {auth.current_user()}"
    
    @auth.login_required(role='admin')
    def admin_route():
        return "Admin only"
    """

User Information

Access current authenticated user information within protected routes.

def current_user(self):
    """
    Get current authenticated user object.
    
    Returns:
    User object returned by verify_password callback, or None if not authenticated
    """

def username(self):
    """
    Get current authenticated username.
    
    Returns:
    str: Username from authentication credentials, or empty string if not authenticated
    """

Usage Examples

Basic Password Verification

from flask import Flask
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {
    "john": "hello",
    "susan": "bye"
}

@auth.verify_password
def verify_password(username, password):
    if username in users and users[username] == password:
        return username

@app.route('/')
@auth.login_required
def index():
    return f"Hello, {auth.current_user()}"

Hashed Password Storage

from flask import Flask
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
auth = HTTPBasicAuth()

users = {
    "john": generate_password_hash("hello"),
    "susan": generate_password_hash("bye")
}

@auth.verify_password
def verify_password(username, password):
    if username in users and check_password_hash(users.get(username), password):
        return username

@app.route('/')
@auth.login_required
def index():
    return f"Hello, {auth.current_user()}"

Custom Password Hashing

from flask import Flask
from flask_httpauth import HTTPBasicAuth
import hashlib

app = Flask(__name__)
auth = HTTPBasicAuth()

@auth.hash_password
def hash_password(password):
    return hashlib.md5(password.encode('utf-8')).hexdigest()

@auth.verify_password
def verify_password(username, password):
    # Password is automatically hashed before verification
    stored_password = get_password_hash(username)
    return username if stored_password else None

Error Handling

Basic authentication automatically handles authentication errors with appropriate HTTP status codes:

  • 401 Unauthorized: Invalid credentials or missing authentication
  • 403 Forbidden: Valid credentials but insufficient role permissions
  • WWW-Authenticate header: Automatically added with realm information

Custom error handling can be implemented using the error_handler decorator inherited from the base HTTPAuth class.

Install with Tessl CLI

npx tessl i tessl/pypi-flask-httpauth

docs

basic-auth.md

digest-auth.md

index.md

multi-auth.md

roles.md

token-auth.md

tile.json