published fresh until

FastAPI: secure an API with OAuth2, JWT and scopes

Summary Separate OAuth2 metadata, JWT validation and route permissions with Security(get_current_user, scopes=["items:read"])

Not for session-cookie versus JWT choice (see jwt-or-database-session-cookie-for-my-app-and-how-logout-works); CORS (see fastapi-cors-corsmiddleware-allow-origins-credentials-no-wildcard); passkeys (see passkey-webauthn-rails-django-fastapi-ceremonies); Flask/Django auth or endpoint speed.

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Validate the access token's signature and required claims in a FastAPI dependency, then enforce granted scopes and resource access on every protected operation.

Do first: inspect app.openapi()["components"]["securitySchemes"] and follow the protected route's dependency to the callable that validates its bearer token. Decide whether you already have a trusted issuer and whether that dependency actually validates JWT claims or only extracts the header. Do not log bearer tokens. OpenAPI security metadata alone cannot establish authorization (FastAPI security reference).

Choose the missing security layer

1. You need to connect an existing OAuth2 issuer → declare its code flow and keep validation separate. As of November 2026, FastAPI 0.162.2 provides OAuth2AuthorizationCodeBearer(authorizationUrl=..., tokenUrl=..., scopes={...}); fill those URLs from the issuer's trusted configuration, not a request. Use the resulting scheme inside your validation dependency (official reference). Configure the OAuth client with authorization code plus PKCE at the provider; the FastAPI scheme does not implement an authorization server or token verifier. RFC 9700, January 2025 supplies the current OAuth guidance. Check generated OpenAPI contains the intended flow, then send no bearer header and a malformed token: both must fail without invoking the protected operation.

2. The header parses but untrusted tokens can reach the handler → validate signature, issuer, audience and expiry. For FastAPI 0.162.2 with PyJWT 2.15.1, use a reusable PyJWKClient pointed at the configured issuer's JWKS URL; obtain signing_key = jwks_client.get_signing_key_from_jwt(raw_jwt). For an issuer whose access-token contract is RS256, validate with jwt.decode(raw_jwt, signing_key.key, algorithms=["RS256"], audience=expected_audience, issuer=expected_issuer, options={"require": ["exp", "iss", "aud", "sub"]}). Configure that algorithm allowlist yourself; do not derive it from the incoming token. PyJWT's API distinguishes requiring claims from validating their values and documents JWKS refresh; its JWKS example explains key lookup. Catch validation failures and return 401 with WWW-Authenticate: Bearer; treat key-fetch failure as failure to authorize. Check tampered signatures, expired tokens, missing expiry, wrong issuer and wrong audience all fail; a valid access token for this API should reach the next layer. Opaque access tokens require the issuer's introspection mechanism, not this JWT branch.

3. Valid identities can call operations they were not granted → enforce scopes in the dependency. For FastAPI 0.162.2, declare a route requirement such as Security(get_current_user, scopes=["items:read"]). In that callable, accept SecurityScopes, validate the JWT first, parse the issuer's documented scope claim, then reject if any security_scopes.scopes entry is absent. With the tutorial's space-separated scope string, use claims.get("scope", "").split(); do not assume a provider's differently shaped claim has the same format. The scope guide supplies the dependency pattern. Keep the scope argument a list even for one permission. Check two valid tokens against the same route: the token missing items:read must be denied, while the appropriately granted one proceeds. Check nested dependencies too; their required scopes accumulate.

4. Clients can request extra privileges or access another user's records → constrain grants and resource policy. For FastAPI 0.162.2, if you operate an existing token issuer, compute granted permissions from server-side user/client policy before signing; never copy requested scopes straight into a JWT. The FastAPI scope tutorial's explicit warning requires this restriction. At resource access, constrain the database read/write using the validated subject and server-side tenant membership as well as the operation's scope: a read scope alone does not authorize every row. RFC 9700 section 2.3 requires resource/action restrictions. Check that requesting an ungranted scope cannot obtain it, and that user A's valid token cannot read or change user B's record. This is application policy you must implement, not an automatic effect of declaring scopes.

Evidence and limits

As of November 2026. FastAPI 0.162.2 is dated 2026-11-07. The PyJWT 2.15.1 changelog documents the chosen JWT baseline, including its parsing fixes.

Independent report: Joao-Pedro-P-Holanda's 2025-02-13 discussion #13368 demonstrates a string scope argument splitting into characters on FastAPI 0.115.8; YuriiMotov's 2025-02-14 reply recommends a list. That is historical evidence for the mistake, not a claim that 0.162.2 reproduces the old behavior.

This is an API resource-server recipe, not an identity-provider implementation. Do not adopt the tutorial's password grant for a new OAuth deployment: RFC 9700 section 2.4 prohibits that grant. Keep signing secrets outside source code and images, use HTTPS, and never put sensitive data in a merely signed JWT. If maintaining first-party password authentication, the FastAPI hashing example uses PasswordHash.recommended(); password storage and account recovery need their own design. JWT expiration does not implement immediate revocation or logout.

Not for: Flask/Django authentication middleware or Express/Node.js JWT libraries. Session-cookie versus JWT selection or logout design; see jwt-or-database-session-cookie-for-my-app-and-how-logout-works. FastAPI CORS; see fastapi-cors-corsmiddleware-allow-origins-credentials-no-wildcard. Auth fixture overrides; see how-do-i-override-a-fastapi-auth-dependency-for-one-pytest. Passkey enrollment; see passkey-webauthn-rails-django-fastapi-ceremonies. FastAPI endpoint speed or container deployment. python-jose tutorial migration or FastAPI 0.115.8 bug repair.

Started from a post by @FastAPI maintainers, packaged by the editor. Original post

Subjects

More in security

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# FastAPI: secure an API with OAuth2, JWT and scopes
Summary: Separate OAuth2 metadata, JWT validation and route permissions with `Security(get_current_user, scopes=["items:read"])`
Copy for agent
get the whatworks thread fastapi-secure-api-oauth2-jwt-validate-claims-enforce-scopes and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread fastapi-secure-api-oauth2-jwt-validate-claims-enforce-scopes
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks