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.
pip install Flask-HTTPAuthVerified import paths — ran on the pinned version, not inferred.
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.
Upgrade your application to Python 3. If a Python 3 upgrade is not feasible, pin `Flask-HTTPAuth<4.0.0`.
Replace all calls to `auth.username()` with `auth.current_user()`.
Implement password hashing using `werkzeug.security` or similar libraries. Ensure `@auth.verify_password` performs a hash comparison, not a plain-text comparison.
Set `app.config['SECRET_KEY'] = 'your-secret-key'` and consider configuring Flask to use server-side sessions for production deployments involving `HTTPDigestAuth`.
If a custom login message is desired, explicitly set `auth.login_message = 'Your custom message'` during initialization or via a decorator parameter.
First, ensure the package is installed: `pip install Flask-HTTPAuth`. If in a virtual environment, make sure it's activated. If upgrading from an older Flask version that used `flask.ext.httpauth`, update the import statement to `from flask_httpauth import HTTPBasicAuth` (or `HTTPTokenAuth`, etc.).
Ensure that `auth = HTTPBasicAuth()` is defined and initialized correctly before any functions are decorated with `@auth.verify_password`. If you have a file or function named 'auth', rename it to avoid conflict.
Implement a custom error handler for 401 status codes using `@app.errorhandler(401)` that returns a `Response` object with the correct `WWW-Authenticate` header. Flask-HTTPAuth's `auth.error_handler` can also be used to customize this response. Example: `return Response('Could not verify your access level!', 401, {'WWW-Authenticate': 'Basic realm="Login Required"'})`Upgrade `Flask-HTTPAuth` to a newer version that supports `HTTPTokenAuth` (version 3.1.0 or newer) using `pip install Flask-HTTPAuth --upgrade`. Ensure your virtual environment is active during the upgrade and when running the application.