Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 72 ยท Authentication and Security

Building a Login System

Build a complete Flask login system from scratch with hashed passwords, session-based authentication, a login_required decorator and safe redirects after login.

Almost every real web app needs to know who is using it. A login system answers that question: visitors register an account, log in to prove who they are, and log out when they are done. Between those steps the app must remember the user across requests, even though HTTP itself has no memory.

In this lesson you will build all of it by hand, using only what you have already learned: hashed passwords from Password Hashing, the signed session cookie, flash messages and a decorator. Writing it yourself once shows you exactly what extensions like Flask-Login automate for you, which makes the extension easier to trust and to debug.

The idea: remember the user id in the session

Authentication in Flask usually works like this. When the user proves who they are, you store their user id in the session. The session is a cookie that Flask signs with your SECRET_KEY, so the browser sends it back on every request and cannot change it without breaking the signature. On each request you read the id from the session, load the user, and decide what to show.

sequenceDiagram
    participant B as Browser
    participant F as Flask
    B->>F: POST /login (email, password)
    F->>F: check_password_hash(...)
    F-->>B: 302 to /dashboard + session cookie (user_id=1)
    B->>F: GET /dashboard (cookie sent)
    F->>F: g.user = load user 1
    F-->>B: 200 Hello, [email protected]
    B->>F: POST /logout
    F-->>B: 302 to / + empty session

The cookie is the only thing that links the requests; the server checks it every time.

Never store the password, or anything sensitive, in the session. The cookie is signed, not encrypted: anyone holding it can read what is inside, as you will see later in this lesson.

Registering, logging in and out

The following app keeps users in a dictionary so the focus stays on the flow. In a real project that dictionary becomes a table (see Flask-SQLAlchemy models); the view code barely changes. Read the comments, then run it.

Python Register, log in and log out

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.

Several details are worth pointing out:

  • Normalize emails. .strip().lower() stops [email protected] and [email protected] from becoming two accounts.
  • One generic failure message. Both an unknown email and a wrong password produce "Wrong email or password.", so an attacker cannot use the form to discover which addresses are registered.
  • session.clear() before logging in. Starting from an empty session avoids carrying over data from an earlier visitor on a shared browser.
  • Logout is a POST. A GET route that changes state can be triggered by an image tag on another site. Use a small form with a button for logout. (The web security lesson explains why, and adds CSRF tokens for forms like this.)
  • Redirect after POST. Every handler that changes state ends in a redirect, the Post/Redirect/Get pattern from Handling HTML forms.
  • g.user in before_request. The user is loaded once per request, and any view or template can use it. This is the hook and g pattern from the previous chapter.

Protecting pages with login_required

The dashboard checks g.user by hand. With ten protected pages that check would be pasted ten times. A decorator wraps a view with the check, so you write the rule once and apply it with one line. If decorators are new to you, read Python decorators first.

A good login_required does three things:

  1. Lets the request through when g.user exists.
  2. Otherwise redirects to the login page and remembers where the user wanted to go, in a next query parameter.
  3. After login, sends the user to that page, but only if the target is on your own site.

The third point matters. If you redirect to whatever next contains, an attacker can send a victim a link like /login?next=https://evil.example/login. After the real login, the victim lands on a fake page that looks the same. This is called an open redirect. Accept only relative paths on your own host.

Python login_required with a safe next redirect

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.

functools.wraps copies the original function's name onto the wrapper. Without it every protected view would be named wrapped, and Flask would complain about duplicate endpoints. Also note that login_required is placed under @app.get(...), so the route is registered for the already-wrapped function.

Check redirect targets against an allowlist of shapes you accept (a path that starts with a single /), not a denylist of bad strings. Browsers treat some odd inputs, such as //host or a backslash, as pointing to another site.

Because the session lives in a cookie, it helps to see what the browser holds. Flask serializes the session to JSON, adds a timestamp and signs it. The result is tamper-proof but readable. You can ask Flask's own serializer to open a cookie for you, and you can prove that changing it breaks the signature.

Python Reading and tampering with the session 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.

Two lessons follow. First, never put secrets in the session, because the user can read it. Second, keep SECRET_KEY secret and stable: if it leaks, anyone can forge a login, and if it changes, every logged-in user is signed out.

Limits of a hand-made login

What you built covers the basics. A production system adds more:

  • Rate limiting on the login route to slow password guessing.
  • Session lifetime. Mark logged-in sessions permanent with a sensible PERMANENT_SESSION_LIFETIME, or leave them as browser-session cookies.
  • "Remember me" with a long-lived, separate cookie.
  • Secure cookie flags: SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY and SESSION_COOKIE_SAMESITE, covered in Cookies and Web Security Essentials.
  • Password reset and email verification, which need signed, expiring tokens.

An extension takes care of several of these for you, and the next lesson shows how.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What do you normally store in the session after a successful login?

    Store a small identifier such as the user id. The session is signed but readable, so it must never hold passwords or other secrets.
  2. 2. Why should the login form say 'Wrong email or password' for both failures?

    Separate messages let an attacker test which emails are registered. A single message gives nothing away.
  3. 3. Why does the login_required decorator use functools.wraps?

    Without wraps every decorated view would be named 'wrapped', and registering a second one would clash with the first.
  4. 4. A login redirects to the next query value. What is the safest policy?

    Following arbitrary values creates an open redirect that can send users to a phishing page. Accept only paths that start with a single slash.
  5. 5. Can a user edit the data inside Flask's session cookie?

    The cookie is signed, not encrypted. Tampering is detected by the signature check, but the contents are visible.

Summary

  • Log in by verifying the password with check_password_hash, then store the user id in session (after session.clear()).
  • Load the current user once per request in a before_request hook and keep it on g.
  • Log out by clearing the session, using a POST request.
  • A login_required decorator centralizes the check; remember the requested page in next and redirect back only to safe, local paths.
  • The session cookie is signed but readable, so keep the id in it and nothing secret.
  • Use one generic error message for failed logins and normalize emails before storing or comparing them.

Next: Flask-Login, the extension that automates sessions, user loading and "remember me".