Authentication and Session Security

Authentication and Session Security in Flask: When you check in at a large hotel, the clerk encodes a plastic keycard on a machine behind the counter.

The Analogy: The Hotel Keycard and the Front Desk

When you check in at a large hotel, the clerk encodes a plastic keycard on a machine behind the counter. The card carries only two useful facts: your room number and a checkout time. Before it hands the card over, the machine stamps it with a magnetic pattern that only the hotel's own encoders know how to produce, and every door reader in the building is wired to trust any card bearing that pattern. You walk to your room, the reader sees a valid stamp and the right room number, and the door opens. Nobody at the door knows your name; the card is the whole conversation.

The card is readable but not forgeable, and the difference is the entire point. A guest can glance at the sleeve and see "Room 402," and someone with a thirty-dollar reader could dump the bytes off the stripe in the lift. None of that is a breach, because the room number was never a secret. What a guest cannot do is manufacture a card for Room 403, because cutting a card that the readers will accept requires the encoder's master key, and that key lives behind the counter. The stamp makes the card tamper-evident, not confidential.

What the desk keeps and what it hands out are deliberately different things. Your credit-card number, your address, your booking history stay in the folio behind the counter; the card in your pocket carries only a short folio number that lets the desk find the rest. And the hotel never writes your personal room-safe PIN into that folio in plain ink: it keeps only a scrambled imprint that lets a clerk confirm a PIN you type but can never be read back into the original digits. The master key that drives the encoder is the one secret that matters more than any lock in the building, because a copy of it cuts a valid card for every room at once.

One chain learned this the expensive way. Every property used the same factory-default master key, so a stamp made in one city was honored in another. The cards had the guest's loyalty tier and a "manager override: yes" flag printed right onto the stripe, and the readers simply believed whatever the stripe said. Worst of all, at check-in the desk reused whatever card a guest was already carrying instead of wiping it. A guest with a cheap card writer flipped his own override flag to "yes," re-stamped the card with the master key that was no secret at all, and let himself into the manager's office; and because cards were never wiped, the next guest to be handed a recycled card inherited the previous holder's access. Every one of those was a real, independent mistake, and each has an exact counterpart in how a Flask session goes wrong.


Syntax or Core Structure

Flask gives you exactly one authentication primitive: a signed cookie called the session. Everything else -- user storage, password hashing, login flows, tokens -- you assemble yourself. That is the trade-off of a micro-framework, and it is the area where a wrong assembly is most expensive. The session behaves like a dictionary that survives from one request to the next by riding in a cookie:

from flask import Flask, session, jsonify

app = Flask(__name__)
app.secret_key = "demo-only-not-for-production"


@app.post("/login-as/<int:uid>")
def login_as(uid):
    session.clear()                 # drop anything from before this login
    session["user_id"] = uid        # store only an identifier
    return jsonify(logged_in=uid)


@app.get("/whoami")
def whoami():
    return jsonify(user_id=session.get("user_id"))


@app.post("/logout")
def logout():
    session.clear()
    return jsonify(logged_out=True)


client = app.test_client()
print(client.get("/whoami").get_json())   # before login
client.post("/login-as/42")
print(client.get("/whoami").get_json())   # cookie carries the session forward
client.post("/logout")
print(client.get("/whoami").get_json())   # cleared

Output:

{'user_id': None}
{'user_id': 42}
{'user_id': None}

The test client keeps cookies between calls exactly as a browser would, so the user_id set during /login-as is still visible at /whoami on the next request. Note the two disciplines already present: the session holds an identifier, not the user's data, and every login begins with session.clear(). Both matter for reasons the next section makes concrete.


Technical Depth: How the Cookie Is Protected, and What It Cannot Protect

The session is signed, not encrypted

Flask serialises the session dictionary to JSON, signs it with your SECRET_KEY, and sends it as a cookie. The signature is what the door reader's trusted stamp is in the analogy: the client cannot alter the contents without the tampering being detected. It does not mean the client cannot read the contents -- the payload is base64, decodable by anyone holding the cookie. Flask signs the cookie with the itsdangerous library; the block below drives that library directly so you can see both properties at once:

from itsdangerous import URLSafeSerializer, BadSignature
import base64

serializer = URLSafeSerializer("server-secret-key")
token = serializer.dumps({"user_id": 7, "role": "member"})

payload = token.split(".")[0]
padded = payload + "=" * (-len(payload) % 4)
print("readable:", base64.urlsafe_b64decode(padded).decode())   # no encryption

print("valid load:", serializer.loads(token))                   # server trusts it

tampered = token[:-1] + ("A" if token[-1] != "A" else "B")
try:
    serializer.loads(tampered)
except BadSignature:
    print("tampered -> BadSignature")                           # edit is rejected

attacker = URLSafeSerializer("wrong-key")
try:
    attacker.loads(token)
except BadSignature:
    print("wrong key -> BadSignature")                          # forgery needs the key

Output:

readable: {"user_id":7,"role":"member"}
valid load: {'user_id': 7, 'role': 'member'}
tampered -> BadSignature
wrong key -> BadSignature

Two rules follow directly. Never put a secret in the session (session["stripe_key"] = ... is readable by the user and by any browser extension they have installed); store an opaque user_id and look the rest up server-side. And treat the cookie flags below as part of the security design, not defaults to leave alone:

Cookie flagWhat it prevents
SESSION_COOKIE_SECUREThe cookie being sent over plain HTTP where it can be sniffed
SESSION_COOKIE_HTTPONLYA cross-site-scripting payload reading the cookie from JavaScript
SESSION_COOKIE_SAMESITEThe cookie riding along on cross-site requests (blunts CSRF)

Secure=True breaks local development over HTTP, which is exactly why it belongs in a production config class rather than the shared base config.

SECRET_KEY is the whole security boundary

A leaked SECRET_KEY is the copied master key from the analogy: it lets an attacker forge a valid session cookie for any user_id they choose, and every authorisation check downstream passes because the request looks legitimately authenticated. Generate it with secrets.token_hex(32), load it from the environment or a secret manager, and never commit it. A key that was ever committed is permanently compromised even after a force-push, so rotate it -- and know that rotation invalidates every existing session, logging all users out, so plan the timing.

Never store a password

The hotel never files your safe PIN in readable ink; it keeps a one-way imprint it can check but not reverse. Werkzeug ships that imprint for you. Never keep the password itself, and never use a fast digest like md5 or sha256 -- speed is a defect here, because it makes brute-forcing a stolen table cheap:

from werkzeug.security import generate_password_hash, check_password_hash

hash1 = generate_password_hash("correct horse", method="pbkdf2:sha256")
hash2 = generate_password_hash("correct horse", method="pbkdf2:sha256")

print("stored equals password:", hash1 == "correct horse")
print("algorithm:", hash1.split(":")[0])
print("verify correct:", check_password_hash(hash1, "correct horse"))
print("verify wrong:", check_password_hash(hash1, "Correct Horse"))
print("two hashes differ (salt):", hash1 != hash2)

Output:

stored equals password: False
algorithm: pbkdf2
verify correct: True
verify wrong: False
two hashes differ (salt): True

The stored value is never the password, and hashing the same password twice yields two different strings because each call mixes in a fresh random salt -- so two users with the same password get different hashes, and an attacker cannot pre-compute a lookup table. check_password_hash re-derives the hash using the salt embedded in the stored string and compares in constant time. This deliberate, salted slowness is the entire defense; treat it as a feature, not a cost to optimise away.


Real World Example: A Login and Ownership API, and the Oracle Hidden in the Fast Path

This service registers users with hashed passwords, logs them in against a signed session, and guards a per-user resource. It uses an in-memory dictionary as the user store so the example runs on its own; a real deployment swaps that for a database, but the authentication and authorisation logic is unchanged. Read the login route closely -- it is written the way most tutorials write it, and it hides a genuine flaw that the paragraphs after the output will name.

from flask import Flask, request, session, jsonify, abort
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = "demo-only-not-for-production"

USERS = {}          # email -> {"id", "password_hash"}
NOTES = {}          # note_id -> {"owner_id", "body"}
_next_user_id = [0]
_next_note_id = [0]


def create_user(email, password):
    _next_user_id[0] += 1
    USERS[email] = {"id": _next_user_id[0],
                    "password_hash": generate_password_hash(password, method="pbkdf2:sha256")}
    return USERS[email]["id"]


@app.post("/login")
def login():
    data = request.get_json(silent=True) or {}
    user = USERS.get(data.get("email", ""))
    if user is None:
        return jsonify(error="invalid_credentials"), 401     # FAST PATH: no hashing
    if not check_password_hash(user["password_hash"], data.get("password", "")):
        return jsonify(error="invalid_credentials"), 401     # same message, slower
    session.clear()                                          # defeat session fixation
    session["user_id"] = user["id"]
    return jsonify(ok=True)

@app.post("/notes")
def create_note():
    uid = session.get("user_id")
    if uid is None:
        return jsonify(error="login_required"), 401
    _next_note_id[0] += 1
    body = (request.get_json(silent=True) or {}).get("body", "")
    NOTES[_next_note_id[0]] = {"owner_id": uid, "body": body}
    return jsonify(id=_next_note_id[0]), 201


@app.delete("/notes/<int:note_id>")
def delete_note(note_id):
    uid = session.get("user_id")
    if uid is None:
        return jsonify(error="login_required"), 401
    note = NOTES.get(note_id)
    if note is None:
        abort(404)
    if note["owner_id"] != uid:                  # authentication is not authorisation
        return jsonify(error="forbidden"), 403
    del NOTES[note_id]
    return jsonify(deleted=note_id)


create_user("ada@example.com", "s3cret-pass")
create_user("cleo@example.com", "hunter2-xyz")

ada = app.test_client()
print("unknown email:", ada.post("/login", json={"email": "nobody@example.com", "password": "x"}).status_code)
print("wrong password:", ada.post("/login", json={"email": "ada@example.com", "password": "nope"}).status_code)
print("good login:", ada.post("/login", json={"email": "ada@example.com", "password": "s3cret-pass"}).status_code)

r = ada.post("/notes", json={"body": "ada note"})
print("create note:", r.status_code, r.get_json())

cleo = app.test_client()
cleo.post("/login", json={"email": "cleo@example.com", "password": "hunter2-xyz"})
print("cleo deletes ada note:", cleo.delete("/notes/1").status_code)
print("ada deletes own note:", ada.delete("/notes/1").get_json())

Output:

unknown email: 401
wrong password: 401
good login: 200
create note: 201 {'id': 1}
cleo deletes ada note: 403
ada deletes own note: {'deleted': 1}

The run proves the three properties that matter. An unknown email and a wrong password return the same 401 with the same body, so the response gives an attacker no valid-email oracle to harvest. A good login sets the session, and from then on the cookie carries the identity forward. And authorisation is enforced independently of authentication: cleo is a fully logged-in user, yet deleting a note she does not own returns 403, while ada deletes her own note successfully. "Who are you" and "may you touch this record" are two different questions, answered by two different checks.

Two defenses in this code are easy to omit. session.clear() runs before user_id is set, so a session identifier an attacker planted in the victim's browser before login is discarded rather than inherited -- the software equivalent of wiping the keycard at check-in instead of re-issuing it. And because notes are addressed by a guessable integer id, login alone would let any authenticated user delete note 1; the owner_id comparison is the line that stops an insecure-direct-object-reference, and it is the line most often missing.

Now look harder at the login route, because it hides the flaw. When the email is unknown, the handler returns on the fast path without ever calling check_password_hash. When the email exists, it runs the deliberately slow salted hash before answering. The message is identical in both cases -- but the time to respond is not.

That timing gap is a genuine side-channel. An attacker who cannot read the message can still measure latency: requests for real accounts are measurably slower because they pay for the hash, so response time alone re-creates exactly the valid-email oracle the equal message was meant to close. The fix is to make both paths cost the same -- compare the supplied password against a fixed dummy hash even when the user is missing -- so the hashing work happens unconditionally. And since an equal-time, equal-message login still does nothing to stop an attacker simply guessing passwords in a loop, it must be paired with per-account and per-IP rate limiting and lockout, which a later module builds. This class of bug ships in real production systems precisely because the code looks correct until you time it.


Common Mistakes

  1. Putting secret data in the session. The session is signed, not encrypted; session["api_key"] = ... or session["ssn"] = ... is base64 the user and their browser extensions can read. Store an opaque user_id and look sensitive data up server-side.
  1. A weak or committed SECRET_KEY. SECRET_KEY = "dev", or any key that was ever committed, lets an attacker forge a cookie for any user_id. Generate it with secrets.token_hex(32), load it from the environment, and rotate any key that leaked.
  1. Hashing passwords with a fast digest, or not hashing at all. md5 and sha256 are built for speed, which makes a stolen table cheap to crack; storing the plaintext is worse. Use generate_password_hash (pbkdf2, scrypt, or bcrypt).
  1. Revealing which half of the login failed. Returning "no such user" for a missing email and "wrong password" otherwise hands an attacker a valid-email oracle. Return one identical message and status for both.
  1. Leaking the same oracle through timing. Returning before hashing when the user is missing makes real accounts measurably slower to reject. Hash against a dummy value even for unknown users so both paths take the same time.
  1. Not clearing the session before login. Without session.clear(), a session id an attacker planted in the victim's browser survives login -- classic session fixation. Clear first, then set user_id.
  1. Treating authentication as authorisation. @login_required proves who the user is, not that they may touch this record. Objects keyed by a guessable integer id need an explicit ownership check, or you have an insecure-direct-object-reference.
  1. Leaving the cookie security flags unset. Without SESSION_COOKIE_SECURE, HTTPONLY, and SAMESITE, the cookie can be sniffed over HTTP, stolen by a cross-site-scripting payload, or replayed cross-site. Set all three in production config.
  1. Logging credentials. A handler that logs full request headers on error records Authorization tokens and posted passwords into a log store half the company can read. Redact credentials before they reach any log.

Best Practices

  • Store only an opaque user_id in the session and resolve everything else server-side; the cookie is readable by the client.
  • Generate SECRET_KEY with secrets.token_hex(32), load it from the environment or a secret manager, and rotate immediately if it ever leaks or was committed.
  • Hash every password with generate_password_hash and verify with check_password_hash; never store plaintext and never substitute a fast digest like md5 or sha256.
  • Make failed logins indistinguishable in both message and timing: return one identical 401, and hash against a dummy value even when the user is missing so both branches cost the same.
  • Call session.clear() at the start of every successful login to discard any pre-login session and defeat fixation.
  • Check resource ownership on every mutation of an id-addressed object; @login_required answers authentication, never authorisation.
  • Set SESSION_COOKIE_SECURE, SESSION_COOKIE_HTTPONLY, and SESSION_COOKIE_SAMESITE in a production config class so local HTTP development is not broken by Secure.
  • Redact credentials and Authorization values before anything reaches the logs, and prefer bearer tokens over cookies for non-browser API clients so CSRF stops being a concern.

Practice Exercises

  1. Apply the timing fix to the login route from the real-world example. Compare the supplied password against a fixed dummy pbkdf2 hash when the email is unknown, so both the missing-user and wrong-password branches perform exactly one hash and take the same time, while still returning the identical 401 body.
  1. Add an ownership-scoped GET /notes/<int:note_id> that returns 404 rather than 403 when the note exists but belongs to another user. Explain in a comment why answering 404 can hide the existence of the record better than 403.
  1. Write a ProductionConfig class that sets the three SESSION_COOKIE_* flags and PERMANENT_SESSION_LIFETIME, then use test_client to log in and assert that the Set-Cookie header on the response contains HttpOnly and SameSite.
  1. Demonstrate the signed-not-encrypted property end to end: log in through test_client, read the raw session cookie, base64-decode its payload to show the user_id is plainly readable, then flip one character of the cookie and confirm the next request is treated as logged out.