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

token-auth.mddocs/

Token Authentication

Token-based HTTP authentication supporting Bearer tokens, JWT tokens, API keys, and custom authentication schemes. Token auth is ideal for API authentication, single-page applications, and stateless authentication patterns.

Capabilities

HTTPTokenAuth Class

Creates a token-based authentication handler with configurable schemes and custom header support.

class HTTPTokenAuth(HTTPAuth):
    def __init__(self, scheme='Bearer', realm=None, header=None):
        """
        Initialize token authentication handler.
        
        Parameters:
        - scheme (str): Authentication scheme, defaults to 'Bearer'
        - realm (str, optional): Authentication realm, defaults to 'Authentication Required'  
        - header (str, optional): Custom header name, defaults to 'Authorization'
        """

Token Verification

Register callback functions for token validation and user identification.

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

Route Protection

Protect Flask routes with token authentication using the login_required decorator.

def login_required(self, f=None, role=None, optional=None):
    """
    Decorator to require token 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_api():
        return {"user": auth.current_user()}
    
    @auth.login_required(role='admin')
    def admin_api():
        return {"message": "Admin access granted"}
    """

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_token callback, or None if not authenticated
    """

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

Usage Examples

Bearer Token Authentication

from flask import Flask
from flask_httpauth import HTTPTokenAuth

app = Flask(__name__)
auth = HTTPTokenAuth('Bearer')

# Simple token storage
tokens = {
    "secret-token-1": "john",
    "secret-token-2": "susan"
}

@auth.verify_token
def verify_token(token):
    if token in tokens:
        return tokens[token]

@app.route('/api/data')
@auth.login_required
def get_data():
    return {"user": auth.current_user(), "data": "sensitive information"}

# Usage: curl -H "Authorization: Bearer secret-token-1" http://localhost:5000/api/data

JWT Token Authentication

from flask import Flask
from flask_httpauth import HTTPTokenAuth
import jwt
from datetime import datetime, timedelta

app = Flask(__name__)
app.config['SECRET_KEY'] = 'jwt-secret-key'
auth = HTTPTokenAuth('Bearer')

@auth.verify_token
def verify_token(token):
    try:
        # Decode and verify JWT token
        data = jwt.decode(token, app.config['SECRET_KEY'], algorithms=['HS256'])
        
        # Check expiration
        if data['exp'] < datetime.utcnow().timestamp():
            return None
            
        return data['username']
    except jwt.InvalidTokenError:
        return None

@app.route('/api/protected')
@auth.login_required
def protected():
    return {"message": f"Hello {auth.current_user()}"}

# Generate token example
def generate_token(username):
    payload = {
        'username': username,
        'exp': datetime.utcnow() + timedelta(hours=1)
    }
    return jwt.encode(payload, app.config['SECRET_KEY'], algorithm='HS256')

API Key Authentication

from flask import Flask
from flask_httpauth import HTTPTokenAuth

app = Flask(__name__)
auth = HTTPTokenAuth('ApiKey')

# API key database
api_keys = {
    "key-12345": {"user": "john", "permissions": ["read", "write"]},
    "key-67890": {"user": "susan", "permissions": ["read"]}
}

@auth.verify_token
def verify_api_key(api_key):
    if api_key in api_keys:
        return api_keys[api_key]

@app.route('/api/read')
@auth.login_required
def read_data():
    user_data = auth.current_user()
    if "read" in user_data["permissions"]:
        return {"data": "readable content"}
    return {"error": "Insufficient permissions"}, 403

# Usage: curl -H "Authorization: ApiKey key-12345" http://localhost:5000/api/read

Custom Header Authentication

from flask import Flask
from flask_httpauth import HTTPTokenAuth

app = Flask(__name__)
# Use custom header instead of Authorization
auth = HTTPTokenAuth(scheme='Token', header='X-API-Key')

tokens = {
    "custom-token-123": "john",
    "custom-token-456": "susan"
}

@auth.verify_token
def verify_token(token):
    return tokens.get(token)

@app.route('/api/data')
@auth.login_required  
def get_data():
    return {"user": auth.current_user()}

# Usage: curl -H "X-API-Key: custom-token-123" http://localhost:5000/api/data

Database Token Verification

from flask import Flask
from flask_httpauth import HTTPTokenAuth
import hashlib
import secrets

app = Flask(__name__)
auth = HTTPTokenAuth('Bearer')

class TokenManager:
    def __init__(self):
        # In real apps, use database
        self.tokens = {}
    
    def create_token(self, username):
        token = secrets.token_urlsafe(32)
        token_hash = hashlib.sha256(token.encode()).hexdigest()
        self.tokens[token_hash] = {
            'username': username,
            'created': datetime.utcnow()
        }
        return token
    
    def verify_token(self, token):
        token_hash = hashlib.sha256(token.encode()).hexdigest()
        token_data = self.tokens.get(token_hash)
        
        if token_data:
            # Check if token is still valid (24 hours)
            if datetime.utcnow() - token_data['created'] < timedelta(hours=24):
                return token_data['username']
            else:
                # Remove expired token
                del self.tokens[token_hash]
        
        return None

token_manager = TokenManager()

@auth.verify_token
def verify_token(token):
    return token_manager.verify_token(token)

@app.route('/login', methods=['POST'])
def login():
    # Simplified login - in real apps, verify username/password
    username = request.json.get('username')
    token = token_manager.create_token(username)
    return {"token": token}

@app.route('/api/protected')
@auth.login_required
def protected():
    return {"user": auth.current_user()}

Token Schemes

Flask-HTTPAuth supports various token authentication schemes:

  • Bearer: Standard OAuth 2.0 bearer tokens (Authorization: Bearer <token>)
  • Token: Simple token scheme (Authorization: Token <token>)
  • ApiKey: API key scheme (Authorization: ApiKey <key>)
  • Custom: Any custom scheme name (Authorization: CustomScheme <token>)

Error Handling

Token authentication handles authentication errors automatically:

  • 401 Unauthorized: Invalid token, expired token, or missing authentication
  • 403 Forbidden: Valid token but insufficient role permissions
  • WWW-Authenticate header: Automatically added with scheme information
  • Token Validation: Automatic token extraction and verification

Custom error responses 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