Flask-HTTPAuth Documentation
repository·main·Indexed 23 days ago
https://github.com/miguelgrinberg/flask-httpauthA Flask extension providing support for Basic, Digest, and Token-based HTTP authentication for Flask routes. It includes features such as the MultiAuth class for multiple authentication schemes, role-based access control (RBAC) via the @auth.get_user_roles decorator, and support for custom token schemes like Bearer tokens. Version 4.8.2.dev0.
What's inside Flask-HTTPAuth
- Flask-HTTPAuth is a Flask extension designed to simplify the implementation of HTTP authentication within Flask routes. It provides a streamlined way to protect specific endpoints using various authentication methods.
Use Multiple Authentication Schemes with MultiAuth
mainTheMultiAuthclass allows you to protect a route with multiple authentication methods. Access is granted if any one of the authentication methods validates successfully. This is useful for supporting both standard user logins (Basic) and API clients (Token).Implement Role-Based Access Control (RBAC)
mainFlask-HTTPAuth provides a role-based system to filter access to routes.
- Define User Roles: Implement a function that returns a list of roles for a user and decorate it with
@auth.get_user_roles. - Restrict Routes: Use the
roleargument in the@auth.login_requireddecorator.
Role Argument Syntax:
- Single role:
role='admin' - List of roles (OR logic):
role=['admin', 'moderator'] - Nested roles (complex logic):
role=['user', ['moderator', 'contributor']](matches if user is a 'user' OR has both 'moderator' and 'contributor' roles).
@auth.get_user_roles def get_user_roles(user): return user.get_roles() @app.route('/admin') @auth.login_required(role='admin') def admins_only(): return "Hello {}, you are an admin!".format(auth.current_user()) @app.route('/admin') @auth.login_required(role=['admin', 'moderator']) def admins_only(): return "Hello {}, you are an admin or a moderator!".format(auth.current_user()) @app.route('/admin') @auth.login_required(role=['user', ['moderator', 'contributor']]) def admins_only(): return "Hello {}, you are a user or a moderator/contributor!".format(auth.current_user())- Define User Roles: Implement a function that returns a list of roles for a user and decorate it with
Install Flask-HTTPAuth
mainInstall the package using
pip:pip install flask-httpauthInstall Flask-HTTPAuth via pip
mainInstall the extension using pip to add Basic, Digest, and Token HTTP authentication support to your Flask application.
pip install Flask-HTTPAuthChoose between 'flask' and 'flask_small' Sphinx themes
mainThis repository provides two distinct themes:
'flask': The standard documentation theme designed for large projects.'flask_small': A compact, one-page theme intended for small Flask addon libraries.
Use Flask Sphinx Styles in your documentation
mainTo use these Sphinx themes in your project's documentation, follow these steps:
- Place the
_themesfolder into your documentation directory (or use a git submodule to include it). - Update your Sphinx
conf.pyfile to include the theme path and set the theme name.
Note: The theme name you set in
html_themedepends on whether you want the standard large-project theme or the small one-page theme.import os import sys sys.path.append(os.path.abspath('_themes')) html_theme_path = ['_themes'] html_theme = 'flask'- Place the
Deployment: Ensure Authorization Headers are Passed
mainSome web servers (like Apache with
mod_wsgi) do not pass theAuthorizationheader to the WSGI application by default. If you encounter issues where credentials are not being received, ensure your server is configured to pass them. For Apache/mod_wsgi, set:WSGIPassAuthorization OnImplement Digest Authentication
mainTo use Digest Authentication, instantiate
HTTPDigestAuth. This method requires aSECRET_KEYto be configured in your Flask app. Use the@auth.get_passworddecorator to define a callback that returns the password for a given username if it exists, orNoneotherwise. Protect routes using the@auth.login_requireddecorator. You can retrieve the authenticated username viaauth.username().from flask import Flask from flask_httpauth import HTTPDigestAuth app = Flask(__name__) app.config['SECRET_KEY'] = 'secret key here' auth = HTTPDigestAuth() users = { "john": "hello", "susan": "bye" } @auth.get_password def get_pw(username): if username in users: return users.get(username) return None @app.route('/') @auth.login_required def index(): return "Hello, %s!" % auth.username() if __name__ == '__main__': app.run()Implement Basic Authentication
mainTo use Basic Authentication, instantiate
HTTPBasicAuthand use the@auth.verify_passworddecorator to define how users are validated. The callback should return the username if authentication is successful, orNoneif it fails. Protect routes using the@auth.login_requireddecorator. You can retrieve the authenticated user viaauth.current_user().from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() users = { "john": generate_password_hash("hello"), "susan": generate_password_hash("bye") } @auth.verify_password def verify_password(username, password): if username in users and \ check_password_hash(users.get(username), password): return username @app.route('/') @auth.login_required def index(): return "Hello, %s!" % auth.current_user() if __name__ == '__main__': app.run()Implement HTTP Basic Authentication
mainTo use Basic authentication, use the
HTTPBasicAuthclass. You must implement a function decorated with@auth.verify_passwordwhich receives theusernameandpassword.- If credentials are valid, return the user object.
- If credentials are invalid, return
NoneorFalse. - Use
@auth.login_requiredto protect routes. - Access the authenticated user via
auth.current_user().
from flask import Flask from flask_httpauth import HTTPBasicAuth from werkzeug.security import generate_password_hash, check_password_hash app = Flask(__name__) auth = HTTPBasicAuth() users = { "john": generate_password_hash("hello"), "susan": generate_password_hash("bye") } @auth.verify_password def verify_password(username, password): if username in users and \ check_password_hash(users.get(username), password): return username @app.route('/') @auth.login_required def index(): return "Hello, {}!".format(auth.current_user()) if __name__ == '__main__': app.run()Implement HTTP Digest Authentication
mainTo use Digest authentication, use the
HTTPDigestAuthclass. You must implement a function decorated with@auth.get_passwordwhich receives theusernameand returns the associated password.Security Note: Digest authentication requires storing challenge data. By default, Flask-HTTPAuth uses the Flask session. For security, it is recommended to use server-side sessions (e.g., via
Flask-SessionorFlask-KVSession) rather than default cookie-based sessions to prevent challenge data from being captured in cookies.from flask import Flask from flask_httpauth import HTTPDigestAuth app = Flask(__name__) app.config['SECRET_KEY'] = 'secret key here' auth = HTTPDigestAuth() users = { "john": "hello", "susan": "bye" } @auth.get_password def get_pw(username): if username in users: return users.get(username) return None @app.route('/') @auth.login_required def index(): return "Hello, {}!".format(auth.username()) if __name__ == '__main__': app.run()