HTTP Authentication for Flask

4.8.1 · active · verified Fri Apr 10

Flask-HTTPAuth is a Flask extension that simplifies the use of HTTP authentication with Flask routes. It currently supports Basic, Digest, and Token authentication schemes. The library is actively maintained with regular releases, typically every few months, ensuring compatibility with the latest Flask versions and addressing security concerns.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic HTTP authentication using `HTTPBasicAuth` and `verify_password` for secure password handling. It uses environment variables for mock user passwords for demonstration purposes, which should be replaced by a secure user management system in production.

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

app = Flask(__name__)
auth = HTTPBasicAuth()

# In a real application, fetch from a database or secure configuration
users = {
    "john": generate_password_hash(os.environ.get('JOHN_PASSWORD', 'hello')),
    "susan": generate_password_hash(os.environ.get('SUSAN_PASSWORD', 'bye'))
}

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

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

@app.route('/public')
def public_route():
    return "This is a public route."

if __name__ == '__main__':
    # Example of setting environment variables for quick testing:
    # export JOHN_PASSWORD=secret_john
    # export SUSAN_PASSWORD=secret_susan
    app.run(debug=True)

view raw JSON →