Skip to content
Visual explainer 4h to learn 5 steps

Authenticate requests and isolate tenants

Validate tokens from an identity provider and enforce tenant ownership on every query.

By Invicly Tech, , in FastAPI with Python for AI Backends. About 12 minutes to read.

Topic 8 of 29

In short

The API does not handle passwords. An identity provider signs in the user and issues a token; FastAPI checks its signature, issuer, audience and expiry on every request, then reads the user and tenant IDs from it. Every query is then scoped to that tenant on the server, so a valid user from one company can never read another company's documents.

Think of it like this: The token is a visitor badge from reception: the guard checks it is genuine and in date, and the badge's floor number, not the visitor's word, decides which doors open.

Explained simply

Authentication means proving who you are. Authorisation means deciding what you are allowed to do. The document Q&A service needs both: it must know which user is calling, and it must make sure that user only sees their own company's documents.

We do not build a login system ourselves. Storing passwords, resetting them and adding multi-factor sign-in is hard to get right. Instead, an identity provider such as Microsoft Entra ID, Auth0 or Keycloak signs the user in and gives the browser a token. Keycloak runs free in Docker, so you can practise without a paid account.

The token is a JWT, a small signed document listing facts called claims: who the user is, who issued the token, which API it is for and when it expires. FastAPI checks the signature with the provider's public key and checks those claims. If anything is wrong, the request gets 401 Unauthorized.

Each customer organisation is a tenant. After the token is verified, the server knows the user and tenant. Every database query then adds tenant_id = the caller's tenant. The client never chooses the tenant; the server does. This stops a user from reading another company's data simply by changing an ID in the URL.

Press Play on a diagram to walk through it one step at a time.

SequenceFrom sign-in to a tenant-scoped query
Browser
Identity provider
FastAPI
PostgreSQL
  1. 1Sign in
    Browser to Identity provider: Sign in
  2. 2Signed access token
    Identity provider to Browser: Signed access token
  3. 3GET /documents/42 with Bearer token
    Browser to FastAPI: GET /documents/42 with Bearer token
  4. 4Token valid: SELECT ... WHERE id = 42 AND tenant_id = :t
    FastAPI to PostgreSQL: Token valid: SELECT ... WHERE id = 42 AND tenant_id = :t
  5. 5No row for this tenant
    PostgreSQL to FastAPI: No row for this tenant
  6. 6404 Not Found
    FastAPI to Browser: 404 Not Found
MapWhich status code for which auth failure
Request rejected
  • 401 Unauthorized
    • No token
    • Bad signature
    • Expired or wrong audience
  • 403 Forbidden
    • Valid user, missing scope
    • Admin-only action
  • 404 Not Found
    • Object belongs to another tenant
    • Do not reveal it exists

In depth

What a token check must verify

A JWT has three parts: a header, a payload of claims and a signature. Anyone can read the payload, so it proves nothing until you verify the signature with the identity provider's public key. Fetch the keys from its JWKS URL, cache them and pick the key whose kid matches the token header.

Then check the claims. iss must equal your provider's exact issuer URL. aud must contain your API's identifier, so a token issued for another app is rejected. exp must be in the future, allowing a small leeway of a few seconds for clock skew. Allow only the algorithm you expect, such as RS256, so an attacker cannot switch the token to a weaker one. PyJWT does all of this in jwt.decode when you pass key, algorithms, audience and issuer. Its PyJWKClient fetches keys synchronously, so in an async app fetch and cache them at startup or call it through a thread.

  • Signature: matches a current key from the JWKS
  • iss: exactly your provider's issuer
  • aud: your API, not another app
  • exp and nbf: valid now, with small leeway
  • alg: only the algorithms you allow

From claims to a user and a tenant

After verification, build a small CurrentUser object in a dependency: user ID from sub, tenant ID from a tenant claim or from a membership table keyed by sub, and roles or scopes for coarse permissions. Routes depend on current_user instead of reading the token themselves, so the rules live in one place.

If a user can belong to several tenants, the client may say which one it wants, but the server must confirm membership before using it. A tenant ID that only comes from a header the client controls is a request, not a fact. Treat the user's own database row as the source for things that can change quickly, such as being suspended, because a token stays valid until it expires.

FlowDependency chain for an authorised request
  1. 1
    HTTPBearer

    Reads the Authorization header

  2. 2
    verify_token

    Signature and claims, else 401

  3. 3
    current_user

    sub, tenant, roles; membership check

  4. 4
    require_scope

    Missing permission, else 403

  5. 5
    Repository

    Every query filtered by tenant_id

Enforce ownership on the server, every time

Broken object level authorisation is first in the OWASP API Security Top 10 for good reason: an API that loads /documents/{id} without checking the owner leaks data to anyone who guesses IDs. UUIDs make guessing harder but are not a control.

Put the tenant filter where it cannot be skipped: a repository class created with the caller's tenant, whose every method adds the filter. For defence in depth, PostgreSQL row-level security can enforce the same rule in the database. You enable it on a table, add a policy such as tenant_id = current_setting('app.tenant_id')::uuid, and set that value per transaction with set_config('app.tenant_id', ..., true). Remember that table owners bypass policies unless you use FORCE ROW LEVEL SECURITY, so the app should connect as a separate, non-owner role.

CORS, cookies and CSRF are different problems

CORS is a browser rule. It decides whether JavaScript on one origin may read a response from another origin. It does not stop the request reaching your API, and tools like curl ignore it completely. In FastAPI you configure it with CORSMiddleware and a list of exact allowed origins. Never pair allow_credentials=True with a wildcard origin: Starlette then echoes any origin back, so every site gets credentialed access.

CSRF is a different attack. A hostile site makes the victim's browser send a request that automatically carries the victim's cookies. If your API reads the token from an Authorization header, the browser never attaches it on its own, so classic CSRF does not apply. If you store the session in a cookie, set HttpOnly, Secure and SameSite=Lax or Strict, and add a CSRF token or check the Origin header on state-changing requests.

CompareBearer header versus session cookie
Bearer token in header
  • Client code attaches it
  • Not sent automatically, so classic CSRF does not apply
  • Exposed if an XSS bug can read it
  • Needs CORS for cross-origin calls
Session cookie
  • Browser attaches it automatically
  • Needs SameSite plus CSRF token or Origin check
  • HttpOnly hides it from page scripts
  • Simplest with a same-origin proxy

Learn it in 5 short steps

About 50m each. Track them with a timer in your plan.

  1. 1
    Validate issuer, audience and expiry~50m
  2. 2
    Get the user and tenant from the token~50m
  3. 3
    Enforce ownership on the server~50m
  4. 4
    Separate CORS from cookies and CSRF~50m
  5. 5
    Test cross-tenant access is denied~50m

Key points

  • Authentication answers who the caller is; authorisation answers what they may touch. Do both on the server.
  • Reject tokens with a wrong issuer, wrong audience, bad signature or past expiry, and allow only the algorithms you expect.
  • Take tenant_id from the verified token or a server-side membership lookup, never from the URL, body or a header the client sets.
  • Return 404 for another tenant's resource so you do not reveal that it exists.
  • CORS controls which browser origins may read responses; it does not authenticate anyone or stop CSRF.

Key terms

Tap a card to flip it. 0/6 known

Examples

python
import jwt  # PyJWT

jwks = jwt.PyJWKClient("https://idp.example.com/.well-known/jwks.json")

def verify(token: str) -> dict:
    key = jwks.get_signing_key_from_jwt(token).key
    return jwt.decode(
        token, key,
        algorithms=["RS256"],
        audience="api://ragsvc",
        issuer="https://idp.example.com/",
        options={"require": ["exp", "iss", "aud", "sub"]},
    )
# claims["sub"] is the user; the tenant comes from a claim or a membership table

PyJWT checks signature, expiry, audience and issuer in one call and raises on any failure.

Practise with Keycloak locally instead of a paid tenant

Prerequisites: Docker. Step 1: start Keycloak in development mode with a placeholder admin password. Step 2: in the admin console create a realm named ragsvc, a client for the API, and two users in two groups that stand for tenant A and tenant B; add a mapper that puts the group into a tenant claim. Step 3: get tokens for both users and call the API. Evidence: user A sees only A's documents, and user A asking for B's document ID gets 404. Cleanup: docker rm -f kc. Microsoft Entra ID works the same way and offers free developer options, but this path does not need it.

bash
docker run -d --name kc -p 8080:8080 \
  -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=change-me \
  quay.io/keycloak/keycloak:26.0 start-dev
# issuer: http://localhost:8080/realms/ragsvc
# JWKS:   http://localhost:8080/realms/ragsvc/protocol/openid-connect/certs
curl -H "Authorization: Bearer $TOKEN_A" http://localhost:8000/documents/$DOC_B
# expect: 404
docker rm -f kc

A tenant-scoped dependency and repository

Step 1: current_user verifies the token and returns the user with their tenant. Step 2: a repository is built from that user, so the tenant is fixed before any query runs. Step 3: get() filters by both ID and tenant and raises 404 when nothing matches. Because routes only receive the repository, a new endpoint cannot forget the tenant filter. Write a test with two tenants that asserts the cross-tenant read returns 404.

python
class DocumentRepo:
    def __init__(self, session: AsyncSession, tenant_id: UUID):
        self.s, self.t = session, tenant_id

    async def get(self, doc_id: UUID) -> Document:
        stmt = select(Document).where(
            Document.id == doc_id, Document.tenant_id == self.t)
        doc = await self.s.scalar(stmt)
        if doc is None:
            raise HTTPException(404, "Document not found")
        return doc

def doc_repo(user=Depends(current_user), s=Depends(get_session)):
    return DocumentRepo(s, user.tenant_id)

Quick reference

  • 401: missing or invalid token; 403: valid user without permission; 404: another tenant's object
  • jwt.decode(token, key, algorithms=["RS256"], audience=..., issuer=...)
  • Always pin algorithms; never let the token header choose freely
  • Tenant comes from the verified token or a membership lookup, never from client input alone
  • Return WWW-Authenticate: Bearer with 401 responses
  • CORSMiddleware: exact origins; no wildcard with allow_credentials=True
  • Cookie sessions need SameSite and a CSRF token or Origin check
  • Row-level security is a second fence; table owners bypass it unless FORCE is set

Common mistakes

  • Decoding a token without verifying it, or accepting any algorithm the token header names.
  • Filtering by tenant in some queries but not others; put the filter in one repository or dependency so it cannot be forgotten.
  • Setting allow_origins to every origin together with credentials, and thinking CORS protects the API.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A token's signature and expiry are valid, but its aud is another company app. What should the API do?

Question 2

2Where should the tenant ID used in queries come from?

Question 3

3What does CORS protect against?

Question 4

4User A requests /documents/{id} for a document in tenant B. Which response is best?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Write a FastAPI dependency that reads a bearer token with HTTPBearer and returns 401 with a WWW-Authenticate header when it is missing or invalid.

  2. Exercise 2medium

    Write a pytest test that proves a user from tenant A cannot read tenant B's document, using dependency overrides instead of real tokens.

  3. Exercise 3hard

    Add PostgreSQL row-level security to documents as a second fence, so a query without the tenant filter still returns only the current tenant's rows.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use OAuth2PasswordBearer from the FastAPI tutorial?
That tutorial shows the password flow so you can learn the pieces. For a real product, let an identity provider handle sign-in and have your API only verify the access tokens it issues.
Where should a browser app keep the access token?
Many teams avoid storing tokens in localStorage, because any XSS bug can read it. A common pattern is a same-origin backend or proxy that keeps tokens server-side and gives the browser an HttpOnly session cookie, plus CSRF protection.
How do I log out a user before their token expires?
Signed tokens stay valid until exp, so keep access tokens short-lived, for example a few minutes to an hour, and check a user or session status in the database for sensitive actions.

Go deeper

ShareXLinkedInWhatsApp