Flask-HTTPAuth Documentation

repository·main·Indexed 23 days ago

https://github.com/miguelgrinberg/flask-httpauth

A 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.

Tokens
4.2K
Snippets
12
Records
22
Agent score
79%

What's inside Flask-HTTPAuth

  1. Implement Role-Based Access Control (RBAC)

    main

    Flask-HTTPAuth provides a role-based system to filter access to routes.

    1. Define User Roles: Implement a function that returns a list of roles for a user and decorate it with @auth.get_user_roles.
    2. Restrict Routes: Use the role argument in the @auth.login_required decorator.

    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())
  2. Use Flask Sphinx Styles in your documentation

    main

    To use these Sphinx themes in your project's documentation, follow these steps:

    1. Place the _themes folder into your documentation directory (or use a git submodule to include it).
    2. Update your Sphinx conf.py file to include the theme path and set the theme name.

    Note: The theme name you set in html_theme depends 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'
  3. Deployment: Ensure Authorization Headers are Passed

    main

    Some web servers (like Apache with mod_wsgi) do not pass the Authorization header 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 On

  4. Implement Digest Authentication

    main

    To use Digest Authentication, instantiate HTTPDigestAuth. This method requires a SECRET_KEY to be configured in your Flask app. Use the @auth.get_password decorator to define a callback that returns the password for a given username if it exists, or None otherwise. Protect routes using the @auth.login_required decorator. You can retrieve the authenticated username via auth.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()
  5. Implement Basic Authentication

    main

    To use Basic Authentication, instantiate HTTPBasicAuth and use the @auth.verify_password decorator to define how users are validated. The callback should return the username if authentication is successful, or None if it fails. Protect routes using the @auth.login_required decorator. You can retrieve 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, %s!" % auth.current_user()
    
    if __name__ == '__main__':
        app.run()
  6. Implement HTTP Basic Authentication

    main

    To use Basic authentication, use the HTTPBasicAuth class. You must implement a function decorated with @auth.verify_password which receives the username and password.

    • If credentials are valid, return the user object.
    • If credentials are invalid, return None or False.
    • Use @auth.login_required to 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()
  7. Implement HTTP Digest Authentication

    main

    To use Digest authentication, use the HTTPDigestAuth class. You must implement a function decorated with @auth.get_password which receives the username and 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-Session or Flask-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()