Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 72 ยท REST APIs

API Authentication with Tokens

Secure a Flask API with bearer tokens. Learn the Authorization header, signed tokens with itsdangerous, how JWT works, 401 vs 403 and rate limiting.

A browser user logs in once and Flask remembers them in a session cookie. An API client is different: it is a mobile app, a script or another server, and it often has no cookie jar. Instead, the client sends a token with every request, in the Authorization header. The server checks the token and learns who is calling.

This lesson builds token authentication from first principles. You will read a bearer token, issue a signed token with itsdangerous, see exactly what a JWT is by building one yourself, return the correct 401 and 403 responses, and limit how often a client may call you. As always with security, you will use well-tested building blocks and never invent your own cryptography.

Authentication and authorization

Two different questions come up, and APIs answer them with different status codes:

  • Authentication: who are you? If the token is missing, wrong or expired, answer 401 Unauthorized (confusingly named; it means "unauthenticated") and include a WWW-Authenticate: Bearer header.
  • Authorization: are you allowed to do this? If we know who you are but you may not do this, answer 403 Forbidden. Roles and Permissions covers the checks.
sequenceDiagram
    participant C as Client
    participant A as API
    C->>A: POST /login (username, password)
    A-->>C: 200 {"token": "..."}
    C->>A: GET /me<br/>Authorization: Bearer ...
    A->>A: verify token, find user
    A-->>C: 200 {"user": "ada"}
    C->>A: GET /me (no token)
    A-->>C: 401 + WWW-Authenticate: Bearer

Log in once with credentials, then prove who you are with the token on every later call.

Reading a bearer token

The standard form is Authorization: Bearer <token>. "Bearer" means whoever bears (holds) the token is treated as its owner, so tokens must travel only over HTTPS and be kept secret like passwords. Flask also parses this header for you: request.authorization understands Basic and Bearer schemes.

Two kinds of tokens are common:

Opaque (random) token Self-contained (signed) token
Looks like kP3x... random string payload.timestamp.signature
Server stores the token (or its hash) in a database nothing; it only needs a secret key
Revoking one token easy: delete the row hard: valid until it expires
Lookup cost a database query per request a signature check, no query

Signed tokens with itsdangerous

itsdangerous is the library Flask itself uses to sign session cookies, and it comes installed with Flask. A URLSafeTimedSerializer takes a secret key and can turn any JSON-friendly data into a signed, timestamped string. Anyone can read the data inside, but nobody can change it without the secret, because the signature would no longer match. loads(..., max_age=seconds) also rejects tokens older than a limit.

Python Issue and verify signed tokens

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 token itself changes with every run (it contains a timestamp), so the example prints facts about it instead of the value. Three details deserve attention:

  • The login failure message is the same whether the username or the password was wrong. Telling an attacker which one failed helps them.
  • salt="api-token" separates this use of the key from other uses (sessions, password-reset links). A token signed for one purpose is then not valid for another.
  • A signed token is not encrypted. Do not put secrets in it, only an id and perhaps a role.

What a JWT is

A JSON Web Token (JWT) is the best-known self-contained token format. It looks like xxxxx.yyyyy.zzzzz: three Base64URL-encoded parts joined by dots.

  1. Header: JSON naming the algorithm, such as {"alg": "HS256", "typ": "JWT"}.
  2. Payload: JSON claims, such as sub (subject, the user id), iat (issued at), exp (expires at).
  3. Signature: an HMAC of header.payload with a secret key (HS256), or a signature by a private key (RS256), so others can verify with only the public key.

The idea is exactly what itsdangerous does, in a standard format that other languages and services understand. Building one by hand takes a few lines, and it shows there is no magic. In real projects use a maintained library such as PyJWT; never write your own (read-only note: pip install pyjwt, then jwt.encode(payload, key, algorithm="HS256") and jwt.decode(token, key, algorithms=["HS256"])).

Python A JWT built from scratch (for learning only)

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 famous JWT mistakes are visible in the comments: accepting whatever algorithm the token header claims (the old "alg": "none" attack), and forgetting that the payload is readable by everyone. Verify with a fixed algorithm list, and keep secrets out of claims.

Opaque tokens and revocation

If you must be able to log a user out everywhere or cut off a stolen token immediately, use opaque random tokens and store them. Generate with secrets.token_urlsafe(32) (never random), hand the plain token to the client once, and store only its hash, as you would with a password, so a database leak does not reveal usable tokens.

Python Opaque tokens, stored hashed, with revoke

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.

In a Flask app, lookup would be a database query inside the same token_required decorator you saw above. Many services combine both worlds: short-lived signed access tokens (minutes) plus a stored, revocable refresh token.

Rate limiting

Authentication stops strangers; rate limiting stops a single client (stranger or not) from hammering your API or guessing passwords. The popular extension is Flask-Limiter, usually backed by Redis in production. The idea is simple enough to show with a plain dictionary: count requests per client key in a time window and answer 429 Too Many Requests, with a Retry-After header, once the count is exceeded.

Python A fixed-window rate limiter

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.

This stand-in lives in one process's memory, so it is wrong as soon as you run several worker processes: each would count separately. Real limiters keep the counters in a shared store like Redis. Also remember that behind a proxy request.remote_addr is the proxy, not the user; see Deployment for ProxyFix. Apply the strictest limits to login endpoints.

Token hygiene

  • Send tokens over HTTPS only, in the Authorization header, never in URLs (URLs end up in logs and browser history).
  • Give signed tokens a short life and decide how a user logs out or rotates them.
  • Load the secret key from the environment (Configuration and Environments); rotate it if it leaks (all tokens become invalid).
  • Compare secrets with hmac.compare_digest, not ==, to avoid timing leaks.
  • If the API is called from JavaScript on another origin, CORS matters too (see Web Security Essentials).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A request arrives with no Authorization header at an endpoint that requires a login. Which response is correct?

    401 means the caller is not authenticated. 403 is for callers whose identity is known but who lack permission.
  2. 2. Why does a JWT payload not need the secret key to be read?

    JWT signing gives integrity, not secrecy. Anyone can decode the claims, so never put secrets in them.
  3. 3. What is the main advantage of opaque (stored) tokens over signed self-contained tokens?

    A signed token stays valid until it expires because the server remembers nothing. A stored token can be deleted at once.
  4. 4. What should the server store for an opaque API token?

    Storing the hash means that a database leak does not hand attackers working tokens. The plain token is shown to the client once.
  5. 5. Which status code and header should a rate limiter send when a client has used up its allowance?

    429 is the status for too many requests, and Retry-After tells the client how many seconds to wait.

Summary

  • Clients send Authorization: Bearer <token>; missing or bad tokens get 401 with WWW-Authenticate: Bearer; known users who lack permission get 403.
  • itsdangerous.URLSafeTimedSerializer issues signed, timestamped tokens; loads(token, max_age=...) raises SignatureExpired or BadSignature.
  • A JWT is header.payload.signature: signed, not encrypted. Use a maintained library and a fixed algorithm list.
  • Opaque tokens are random (secrets.token_urlsafe), stored hashed, and can be revoked at once.
  • Rate-limit with 429 and Retry-After, using a shared store in production; protect login endpoints most.
  • Use HTTPS, short lifetimes, secrets from the environment and constant-time comparisons.

Next, make sure all of this keeps working as the code grows by learning to test it in Testing Flask Apps with pytest.