Flask-Login Documentation

repository·main·Indexed 26 days ago

https://github.com/maxcountryman/flask-login

A user session management extension for Flask (version 0.7.0.dev) that handles login, logout, and session persistence. It provides a database-agnostic approach using a LoginManager, UserMixin for user objects, and a user_loader callback. Key features include the @login_required decorator, 'Remember Me' functionality, session protection, fresh login tracking for sensitive actions, and a FlaskLoginClient for automated testing.

Tokens
4.8K
Snippets
14
Records
36
Agent score
85%

What's inside Flask-Login

  1. Overview of Flask-Login

    main

    Flask-Login provides user session management for Flask. It manages common authentication tasks such as logging in, logging out, and maintaining user sessions over time.

    It is database-agnostic and does not require a specific permissions model. To use it, your user objects must implement specific methods (typically via UserMixin), and you must provide a user_loader callback to retrieve users from their ID.

  2. Handle fresh logins and re-authentication

    main

    Flask-Login distinguishes between "fresh" logins (actual authentication) and "non-fresh" logins (e.g., via a "remember me" cookie). Use @login_required for general access and @fresh_login_required for sensitive actions like changing personal information.

    You can customize the re-authentication behavior by configuring the LoginManager or providing a custom handler:

    1. Configure redirect and messages: Set refresh_view, needs_refresh_message, and needs_refresh_message_category on your LoginManager instance.
    2. Custom handler: Use the @login_manager.needs_refresh_handler decorator to provide a custom callback.
    3. Confirm login: Call the confirm_login function to mark a session as fresh again.
    login_manager.refresh_view = "accounts.reauthenticate"
    login_manager.needs_refresh_message =
        u"To protect your account, please reauthenticate to access this page."
    login_manager.needs_refresh_message_category = "info"
    
    @login_manager.needs_refresh_handler
    def refresh():
        # do stuff
        return a_response
  3. Use FlaskLoginClient for automated testing

    main

    Flask-Login provides FlaskLoginClient to simplify testing authenticated routes. By assigning it to app.test_client_class, you can pass a user object directly to app.test_client() to simulate a logged-in user.

    Important: You must use keyword arguments (e.g., user=user) and not positional arguments. You can also pass fresh_login (bool) to specify the freshness of the session.

    from flask_login import FlaskLoginClient
    
    # Setup
    app.test_client_class = FlaskLoginClient
    
    # Usage in tests
    def test_request_with_logged_in_user():
        user = User.query.get(1)
        with app.test_client(user=user) as client:
            # This request has user 1 already logged in!
            client.get("/")
    
        # With fresh login
        with app.test_client(user=user, fresh_login=True) as client:
            client.get("/")
  4. Set up Flask-Login with LoginManager

    main

    To integrate Flask-Login into your Flask application, initialize a LoginManager instance and call init_app(app). Ensure your Flask app has a secret_key configured to handle sessions.

    import flask
    import flask_login
    
    app = flask.Flask(__name__)
    app.secret_key = "super secret string"  # Change this!
    
    login_manager = flask_login.LoginManager()
    login_manager.init_app(app)
  5. Use 'Remember Me' functionality

    main
    To prevent users from being logged out when they close their browser, pass remember=True to login_user(). This saves a tamper-proof cookie on the user's computer. The cookie duration can be controlled via the REMEMBER_COOKIE_DURATION configuration or by passing a duration directly to login_user.
  6. Configure the LoginManager

    main

    The LoginManager class is the central component of Flask-Login. You must create an instance and initialize it with your Flask application object. Because Flask-Login uses sessions by default, you must also ensure your Flask application has a secret_key configured.

    from flask_login import LoginManager
    
    login_manager = LoginManager()
    # ... after creating your Flask app object ...
    login_manager.init_app(app)
  7. Configure session protection

    main

    Session protection helps prevent session hijacking by verifying the user's computer (IP and User Agent) on each request. You can configure this on the LoginManager or via the SESSION_PROTECTION app config.

    Modes:

    • basic: If identifiers don't match, the session is marked as non-fresh. Anything requiring a fresh login will force re-authentication.
    • strong: If identifiers don't match for a non-permanent session, the entire session and remember token are deleted.
    • None: Disables session protection.

    Note: If using the FlaskLoginClient for automated testing, you may need to disable session protection to avoid session rejection.

    login_manager.session_protection = "strong"
    # or
    login_manager.session_protection = None
  8. Configure `needs_refresh` behavior

    main

    When using session protection, you can configure how the application handles users who need to reauthenticate (e.g., to upgrade a 'remembered' session to a 'fresh' session).

    • refresh_view: The name of the view to redirect to when a user needs to reauthenticate.
    • needs_refresh_message: The message flashed when a user is redirected to the reauthentication page.
    • needs_refresh_handler: A method to define custom behavior for when a refresh is required.
  9. Configure Anonymous Users

    main

    By default, current_user returns an AnonymousUserMixin object when no user is logged in. You can provide a custom class or factory function to LoginManager.anonymous_user if you need anonymous users to have specific properties.

    login_manager.anonymous_user = MyAnonymousUser
  10. Customize login redirection and messages

    main

    You can configure how Flask-Login handles unauthorized access via the LoginManager instance:

    • login_view: The endpoint name to redirect to when a user needs to log in (e.g., login_manager.login_view = "users.login").
    • login_message: The message flashed to the user (default: "Please log in to access this page.").
    • login_message_category: The Flask category for the flashed message (e.g., "info").
    • unauthorized_handler: A decorator to customize the behavior when an unauthorized user attempts to access a protected view.