Flask-BasicAuth
Flask-BasicAuth is a Flask extension that provides a straightforward way to add HTTP basic access authentication to specific views or an entire Flask application. The current version is 0.2.0, released in June 2013, indicating a very slow release cadence and a largely unmaintained status.
Warnings
- breaking Basic Authentication sends credentials (username and password) in cleartext over the network, only Base64 encoded, which is easily reversible. It is CRITICAL to use HTTPS/TLS to encrypt the connection between the client and server. Without HTTPS, credentials can be easily intercepted.
- gotcha When deploying Flask-BasicAuth behind a reverse proxy like Nginx or Apache with mod_wsgi, the proxy might strip the `Authorization` header, preventing Flask-BasicAuth from receiving the credentials.
- gotcha The `BASIC_AUTH_FORCE = True` configuration, intended to protect the entire application, has been reported to cause continuous re-prompting for credentials in some browsers due to how authorization headers are handled.
- gotcha Flask-BasicAuth performs a direct string comparison for usernames and passwords (cleartext comparison). It does not include mechanisms for secure password hashing (e.g., bcrypt, scrypt) or storage.
- deprecated This library has not been updated since June 2013, with Python 3 support only officially extending to Python 3.3. It is largely unmaintained, and may not be compatible with newer Flask versions or Python releases, or may lack features and security updates present in more active alternatives.
Install
-
pip install Flask-BasicAuth
Imports
- BasicAuth
from flask_basicauth import BasicAuth
Quickstart
import os
from flask import Flask, render_template_string
from flask_basicauth import BasicAuth
app = Flask(__name__)
app.config['BASIC_AUTH_USERNAME'] = os.environ.get('BASIC_AUTH_USERNAME', 'admin')
app.config['BASIC_AUTH_PASSWORD'] = os.environ.get('BASIC_AUTH_PASSWORD', 'secret')
basic_auth = BasicAuth(app)
@app.route('/')
def index():
return "Welcome!"
@app.route('/secret')
@basic_auth.required
def secret_view():
return render_template_string("<h1>Secret Page</h1><p>Accessed with basic auth.</p>")
if __name__ == '__main__':
# To protect the entire site (e.g., for staging environments):
# app.config['BASIC_AUTH_FORCE'] = True
# Ensure BASIC_AUTH_USERNAME and BASIC_AUTH_PASSWORD are set as environment variables
# or directly in app.config for production.
app.run(debug=True)