Flask-BasicAuth

0.2.0 · maintenance · verified Mon Apr 13

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

Install

Imports

Quickstart

This quickstart initializes a Flask application with Flask-BasicAuth. It demonstrates protecting a single route (`/secret`) using the `@basic_auth.required` decorator. Credentials are loaded from environment variables for security, defaulting to 'admin' and 'secret'. The example also notes how to protect the entire application using `BASIC_AUTH_FORCE = True`.

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)

view raw JSON →