Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 72 ยท Authentication and Security

Flask-Login

Use the Flask-Login extension to manage sessions the easy way. Learn LoginManager, user_loader, UserMixin, login_user, current_user, remember me and unauthorized handlers.

In the previous lesson you wrote a login system by hand: a before_request hook to load the user, a login_required decorator, a safe next redirect, a session that holds the user id. It works, but it is code every Flask project needs and every project gets slightly wrong. Flask-Login is the extension that packages exactly those pieces so you do not have to maintain them.

Flask-Login does not create users, hash passwords or build login forms. It handles one narrow job: remembering which user is logged in between requests. You supply how to find a user by id and how to verify a password (see Password Hashing); it supplies the session handling, the current_user proxy, the login_required decorator, "remember me" cookies and redirects to the login page. In the browser here it installs with micropip.install("flask-login"); on your machine it is pip install flask-login.

The four ingredients

A working setup needs four things:

  1. A LoginManager attached to the app.
  2. A user class that provides a few properties and methods. Inherit from UserMixin and you get sensible defaults for all of them.
  3. A user_loader function that takes the id stored in the session and returns the user (or None).
  4. Calls to login_user(user) and logout_user() in your views.

UserMixin gives your class is_authenticated (true), is_active (true), is_anonymous (false) and get_id(), which returns str(self.id). So the only thing your class must have is an id attribute (or override get_id).

Once set up, current_user is available everywhere, including templates. For a visitor who is not logged in it is an anonymous object whose is_authenticated is False, so you never have to check for None.

flowchart LR
    A["Request with<br/>session cookie"] --> B["Flask-Login reads<br/>user id from session"]
    B --> C["your user_loader(id)"]
    C -->|"user object"| D["current_user = that user"]
    C -->|"None"| E["current_user = anonymous"]
    D --> F["View runs"]
    E --> F

Flask-Login calls your loader lazily, the first time current_user is used in a request.

Python A complete Flask-Login app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare this with your hand-written version. There is no before_request hook, no g.user, no decorator body and no session["user_id"] line: login_user writes the session, user_loader reads it back, and login_required redirects anonymous visitors to the endpoint named in login_view. It also appends ?next=... to the redirect and flashes login_message, which is the message you see after Login page | in the output.

user_loader runs on every request that touches current_user. With a database, that is one query by primary key per request, which is cheap. Keep the loader fast and return None for an unknown id, for example when an account was deleted while its owner was still logged in.

The next parameter is not automatically safe

Flask-Login adds next for you, but your login view decides where to go after login. As in the previous lesson, only follow local paths. The example above is kept short for readability; in your own code, validate it (see open redirects) before redirecting.

Remember me

By default the login lasts as long as the session cookie, which usually ends when the browser closes. Pass remember=True to login_user and Flask-Login also sets a second cookie, remember_token, with a long expiry (365 days by default). On a later visit, when the session is gone, the extension notices the remember cookie, validates it and logs the user in again.

Python Remember me and the extra cookie

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The remember cookie holds the user id plus a hash. Flask-Login marks it HttpOnly so JavaScript cannot read it. You can tune the cookie with settings such as REMEMBER_COOKIE_DURATION, REMEMBER_COOKIE_SECURE, REMEMBER_COOKIE_HTTPONLY and REMEMBER_COOKIE_SAMESITE. For better protection, make get_id() return something that changes when the password changes (such as a hash of the password hash). Then a password change invalidates old cookies, a pattern called an alternative token.

Inactive users, anonymous users and 401 responses

The properties on UserMixin are not decoration. Each one has a job:

Property Meaning Typical use
is_authenticated The user is logged in Show "Log out" instead of "Log in"
is_active The account may log in Return False for banned or unverified accounts
is_anonymous Not a real user True only for the anonymous placeholder

If is_active is false, login_user refuses and returns False. Always check its result when accounts can be disabled.

Some requests should not be answered with a redirect to a login page. An API client expects a 401 status and JSON, not HTML. Register an unauthorized_handler to decide what happens when login_required fails:

Python Inactive accounts and a JSON 401

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same login_required works for both a browser page and an API route; only the failure behavior changes. For the API side in depth, see API authentication with tokens.

Practical tips

  • Store the user id, not the object. Flask-Login already does this: only the id goes into the session.
  • Call logout_user() to log out. It clears the session's user and the remember cookie in one step.
  • Use fresh_login_required for sensitive actions like changing a password. It demands a recent real login rather than a restored remember-me session.
  • Set login_manager.session_protection = "strong" to have Flask-Login compare a fingerprint of the client (IP address and user agent) and log the user out if it changes. The default, "basic", only marks the session as not fresh.
  • Use it in templates with current_user.is_authenticated and current_user.email; current_user is added to the template context automatically.
  • Authorization is separate. Flask-Login only answers "who is this?", not "may they do this?". That is the next lesson, Roles and Permissions.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the function registered with @login_manager.user_loader do?

    Flask-Login stores only the id in the session. On later requests it calls your loader to get the user back.
  2. 2. What does UserMixin provide for your user class?

    UserMixin supplies the four members Flask-Login expects. Your class only needs an id attribute.
  3. 3. What is the effect of login_user(user, remember=True)?

    The extra cookie outlives the session cookie and restores the login on a later visit.
  4. 4. An API view protected by login_required should return JSON 401 instead of a redirect. What do you register?

    unauthorized_handler runs whenever login_required denies a request, so you can branch on the path or the Accept header.
  5. 5. Which question does Flask-Login answer?

    Flask-Login handles identity (authentication). Permissions and roles (authorization) are your own logic.

Summary

  • Flask-Login manages the logged-in user for you: a LoginManager, a user_loader, a UserMixin user class, and login_user / logout_user.
  • current_user works in views and templates; for visitors it is an anonymous object, never None.
  • login_required redirects to login_view and adds next; use unauthorized_handler for JSON APIs.
  • remember=True adds a persistent remember_token cookie; tune it with the REMEMBER_COOKIE_* settings.
  • is_active lets you block disabled accounts, and login_user returns False for them.
  • Flask-Login does identity only. You still hash passwords, validate next and decide permissions yourself.

Next: Roles and Permissions, deciding what each logged-in user is allowed to do.