Skip to content
Tutorials Center
My learning

Topics

Lesson 123 of 149 ยท Data and the Web

FastAPI Authentication: Password Hashing, JWT and OAuth2

Secure a FastAPI app. Hash passwords with bcrypt, issue and verify JWT access tokens, build the OAuth2 password flow, add role checks, and learn when CSRF matters.

Almost every real API needs to answer two questions: who is calling? (authentication) and what are they allowed to do? (authorization). In this lesson you build a small but complete login system on top of FastAPI: safe password storage, a login endpoint that hands out JWT access tokens, protected routes, and role checks such as "only admins can delete users".

Every piece here is real and runs in your browser: bcrypt for passwords, PyJWT for tokens and FastAPI's own OAuth2PasswordBearer security helpers. The only thing missing is a real database, so users live in a dictionary.

Security code is easy to get subtly wrong. The examples teach the ideas and use correct building blocks, but for a production system read the documentation of your libraries, keep secrets out of source code and have someone review the result. Never invent your own password hashing or token format.

Never store passwords, store hashes

If your database leaks and it contains plain passwords, every user is compromised, including on other sites where they reused the password. Instead you store a hash: the output of a one-way function. At login you hash what the user typed and compare.

A general-purpose hash such as SHA-256 is the wrong tool, because it is fast and attackers can try billions of guesses per second. You need a password hashing function that is deliberately slow and adds a random salt (so two users with the same password get different hashes). bcrypt and argon2 are the usual choices.

Python Hashing and checking a password

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 text $2b$10$ at the start of the hash records the algorithm and the cost factor (10 means 2^10 rounds). The salt is stored inside the hash, so you only need one database column. Raise the cost over the years as computers get faster; around 250 ms per hash is a common target on your server. Note that bcrypt only uses the first 72 bytes of a password.

In an application, you install a library with pip install bcrypt (or argon2-cffi, or pwdlib which wraps both with a friendly API). Do not log passwords, do not email them back and never write your own hashing loop.

What is a JWT?

After login, the server must recognize the user on later requests. One approach is a JSON Web Token (JWT): a signed string the client sends back in an Authorization: Bearer <token> header. A JWT has three parts separated by dots: a header, a payload of claims and a signature.

  • The payload is only encoded, not encrypted. Anyone can read it, so never put secrets in it.
  • The signature proves the token was created by someone who knows the server's secret key and that nobody changed the payload.
  • Common claims: sub (subject, the user), exp (expiry time), iat (issued at).
Python Create, read and verify a token

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 habits matter a lot. First, always pass algorithms=[...] when decoding, so an attacker cannot choose a weaker one such as none. Second, keep access tokens short-lived (minutes), because a JWT cannot be revoked before it expires unless you add a denylist. Long sessions use a separate refresh token that is stored server-side and can be revoked.

HS256 signs with one shared secret, which is fine when one service both issues and checks tokens. When many services must verify tokens but only one may issue them, use an asymmetric algorithm such as RS256 or ES256: the private key signs, the public key verifies.

The OAuth2 password flow in FastAPI

FastAPI has built-in support for the OAuth2 password flow, which the interactive docs at /docs understand: they show an Authorize button and send the login form for you. The pieces are:

  1. POST /token receives a form with username and password (OAuth2PasswordRequestForm) and returns {"access_token": ..., "token_type": "bearer"}.
  2. OAuth2PasswordBearer(tokenUrl="token") is a dependency that reads the bearer token from the Authorization header (and answers 401 if it is missing).
  3. A get_current_user dependency decodes the token and loads the user.

Form parsing needs the small python-multipart package (pip install python-multipart).

In a normal project you would write form: Annotated[OAuth2PasswordRequestForm, Depends()], a ready-made class with username, password and scope fields. FastAPI runs class dependencies in a worker thread, and a browser page cannot start threads, so the example below declares the same two form fields directly with Form(). The request and response on the wire are identical, and /docs behaves the same.

Python A complete login system

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.

Study the two failure codes. 401 Unauthorized means "I do not know who you are" (missing, invalid or expired credentials), and carries a WWW-Authenticate header. 403 Forbidden means "I know who you are, and you may not do this".

Notice also that the login endpoint returns the same message for an unknown user and for a wrong password. Telling attackers which usernames exist helps them. A real system also rate-limits /token (for example with a library like slowapi, or at your reverse proxy) to slow down password guessing.

Role checks and scopes

The require_role function is a dependency factory: it returns a dependency configured for the roles you pass. You attach it per route (as above) or to a whole group with APIRouter(dependencies=[Depends(require_role("admin"))]).

Roles are simple. When you need finer control, such as "can read reports but not edit them", look at OAuth2 scopes: strings stored in the token ("scope": "reports:read") that FastAPI can check with Security(get_current_user, scopes=["reports:read"]). Whatever you choose, enforce permissions on the server for every request. Hiding a button in the page is not security.

One more rule: when the token says role: admin but the user was demoted a minute ago, the token still says admin until it expires. For sensitive operations, load the user from the database in get_current_user and trust the database, not the token's copy.

Where does the browser keep the token?

How the client stores the token decides which attacks matter.

Storage Sent automatically? Main risk Defence
Authorization header, token kept in JavaScript memory No XSS can read it Short lifetime, strict Content Security Policy
localStorage No XSS can read it Same, and prefer memory plus refresh cookie
HttpOnly cookie Yes CSRF SameSite, CSRF token, Secure

CSRF (cross-site request forgery) is an attack where a malicious site makes your browser send a request to your API, and the browser helpfully attaches your cookie. It only works when credentials are sent automatically. Tokens put in an Authorization header by your own JavaScript are not attached to requests from other sites, so pure bearer-token APIs are not vulnerable to CSRF (they have the XSS tradeoff instead).

If you use cookies for sessions or tokens, defend like this:

  • Set the cookie with HttpOnly (JavaScript cannot read it), Secure (HTTPS only) and SameSite=Lax or Strict (not sent on cross-site requests).
  • Require a CSRF token for requests that change data: a random value your page sends in a custom header that a foreign site cannot read or set.
  • Never change data with GET requests.
Python
from fastapi import Response

@app.post("/login-cookie")
async def login_cookie(response: Response):
    response.set_cookie(
        "session", token_value,
        httponly=True, secure=True, samesite="lax", max_age=900,
    )
    return {"ok": True}

Production checklist

  • Serve everything over HTTPS; credentials in plain HTTP can be read by anyone on the network.
  • Load SECRET from an environment variable or secret manager, and make it long and random (openssl rand -hex 32). Changing it logs everyone out.
  • Use a real cost for bcrypt (12 is a common starting point). The demo above used 6 to stay fast in the browser.
  • Add rate limiting, account lockout or delay for repeated failures, and log authentication failures.
  • Prefer a maintained identity solution (an OpenID Connect provider such as Keycloak, Auth0 or your cloud's service) when you need social login, MFA, password resets and e-mail verification. Those features are large and easy to get wrong.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is SHA-256 a poor choice for storing passwords?

    Password hashing must be deliberately slow and salted. bcrypt, argon2 and scrypt are designed for that; a plain fast hash is not.
  2. 2. Which statement about a JWT payload is true?

    The signature protects integrity, not secrecy. Keep secrets out of the payload and give tokens an exp claim.
  3. 3. A logged-in member calls DELETE /users/bob, an admin-only route. Which status should the API return?

    The caller is authenticated, so 401 would be wrong. 403 means the identity is known but lacks permission.
  4. 4. Why should you always pass algorithms=[...] to jwt.decode?

    Without an explicit allow-list, the token's own header could steer verification. You decide which algorithms are acceptable.
  5. 5. When is CSRF a real concern?

    CSRF abuses automatic credentials. A bearer token that your own JavaScript adds to a header is not sent by a foreign site, but cookies are, so cookie-based auth needs SameSite and CSRF tokens.

Summary

  • Store salted, slow hashes (bcrypt or argon2) and compare with checkpw; never plain or fast-hashed passwords.
  • A JWT is a signed, readable token with claims such as sub and exp. Verify with an explicit algorithm list and keep lifetimes short.
  • FastAPI's OAuth2PasswordRequestForm, OAuth2PasswordBearer and dependencies give you the login endpoint and protected routes, and /docs understands the flow.
  • Return 401 for missing or bad credentials and 403 for insufficient permission; use the same message for unknown users and wrong passwords.
  • Role checks are dependency factories such as require_role("admin"); enforce them on the server.
  • Bearer headers are exposed to XSS but not CSRF; cookies need HttpOnly, Secure, SameSite and CSRF tokens.
  • Use HTTPS, environment-based secrets, rate limiting and, for complex needs, a dedicated identity provider.

Next: Background Jobs with Celery and RQ.