skip to content

In FastAPI, what do OAuth2AuthorizationCodeBearer and OpenIdConnect do with a request, and what must your own dependency still verify?

level: middleimportance: should knowfreq 25%

answer

  1. declarations for the schema
  2. header in, string out
  3. the class calls itself a stub
  4. the discovery URL is never fetched
  5. signature, issuer, audience, scopes

basics

~20 s

Both only read the Authorization header and describe a scheme in OpenAPI. OAuth2AuthorizationCodeBearer returns the text after Bearer; OpenIdConnect returns the whole header and never fetches its discovery URL. Token validation and scope checks are your dependency's job.

solid answer

~40 s

`OAuth2AuthorizationCodeBearer(authorizationUrl=..., tokenUrl=..., scopes={...})` writes a `flows.authorizationCode` scheme into OpenAPI, so `/docs` can run the code flow against your identity provider. At request time it reads `Authorization`, rejects a missing or non-bearer header, and returns whatever follows `Bearer`, so `Bearer not-a-jwt` reaches your code as `"not-a-jwt"`. `OpenIdConnect(openIdConnectUrl=...)` is weaker still: its docstring calls it a stub that does not use the URL, and it returns the **entire** header value, scheme included, even `Basic ...`. With the default `auto_error=True`, both answer a missing header with 401 and `WWW-Authenticate: Bearer` in FastAPI 0.143. Your dependency must check the scheme where needed, validate the token against the provider's keys and claims, and compare its scopes with `SecurityScopes`.

code

python · 36 lines
python
from typing import Annotated

from fastapi import Depends, FastAPI
from fastapi.security import OAuth2AuthorizationCodeBearer, OpenIdConnect
from fastapi.testclient import TestClient

code_scheme = OAuth2AuthorizationCodeBearer(
    authorizationUrl="https://id.example.com/authorize",
    tokenUrl="https://id.example.com/token",
    scopes={"items:read": "Read items.", "items:write": "Change items."},
)
oidc_scheme = OpenIdConnect(
    openIdConnectUrl="https://id.example.com/.well-known/openid-configuration"
)

app = FastAPI()


@app.get("/code")
def via_code(token: Annotated[str, Depends(code_scheme)]):
    return {"got": token}


@app.get("/oidc")
def via_oidc(header: Annotated[str, Depends(oidc_scheme)]):
    return {"got": header}


client = TestClient(app)
print(client.get("/code", headers={"Authorization": "Bearer not-a-jwt"}).json())
# {'got': 'not-a-jwt'}             <- accepted, never validated
print(client.get("/oidc", headers={"Authorization": "Basic Zm9vOmJhcg=="}).json())
# {'got': 'Basic Zm9vOmJhcg=='}    <- whole header, any scheme
r = client.get("/oidc")
print(r.status_code, r.headers["www-authenticate"], r.json())
# 401 Bearer {'detail': 'Not authenticated'}

go deeper

for a junior

Recall that these classes only pull the header and describe the scheme for /docs; they never decide whether a token is genuine.

for a middle

State what each class returns, the token after Bearer or the whole header, and list the checks a wrapper dependency must add before any route trusts the result.

for a senior

Review an identity-provider integration for routes that depend on the scheme directly, raw headers in logs, and a missing scheme check on the OpenIdConnect value.

for a principal

Make one validated principal dependency the only way routes reach identity, so provider changes and scope rules live in one reviewed place.

## Two classes that describe, not verify FastAPI's security classes live in `fastapi.security`. Each is a callable dependency **and** a description of an OpenAPI security scheme. For the password flow the app usually issues its own tokens. For the two classes here, tokens come from an external **identity provider**, and the classes mostly exist so the schema and the docs UI know about it. ### `OAuth2AuthorizationCodeBearer` Its constructor takes `authorizationUrl`, `tokenUrl`, an optional `refreshUrl`, an optional `scopes` dict (name to description), plus `scheme_name`, `description` and `auto_error`. FastAPI writes a scheme of `type: oauth2` with a `flows.authorizationCode` object holding those URLs and scopes. When a request arrives the instance: 1. reads the `Authorization` header; 2. if it is missing or its scheme is not `Bearer`, raises the not-authenticated error, or returns `None` when `auto_error=False`; 3. otherwise returns the text after `Bearer`. It does not check that the string is a JWT, that it is signed, or that it came from the provider named in `tokenUrl`. `Bearer not-a-jwt` is returned as `"not-a-jwt"`. ### `OpenIdConnect` Its constructor takes `openIdConnectUrl` (the provider's discovery document), plus `scheme_name`, `description` and `auto_error`, and produces a scheme of `type: openIdConnect`. The class's own docstring warns that it is **only a stub** that connects the components with OpenAPI and does not use the URL; you subclass it or wrap it to do real work. Its call is simpler than the OAuth2 classes' call: - a missing header raises the not-authenticated error, or returns `None` with `auto_error=False`; - any present header is returned **whole**, scheme included: `Bearer abc` comes back as `"Bearer abc"`, and `Basic Zm9vOmJhcg==` is accepted too. ## Side by side | | `OAuth2AuthorizationCodeBearer` | `OpenIdConnect` | |---|---|---| | OpenAPI type | `oauth2`, `authorizationCode` flow | `openIdConnect` | | Holds a scopes dict | yes | no | | Accepts a non-`Bearer` header | no | yes | | Returns | token after `Bearer` | the full header value | | Fetches a URL | no | no | | Validates the token | no | no | | Missing header, default `auto_error` | 401, `WWW-Authenticate: Bearer` | 401, `WWW-Authenticate: Bearer` | Both still take part in scope bookkeeping: `Security(oidc_scheme, scopes=["items:read"])` puts `items:read` in the operation's OpenAPI security, but, as with every class here, nothing is enforced by declaring it. ## What your dependency must add A safe wrapper sits between the scheme and the routes. Built from the defender's side, it: - **checks the scheme** when it receives the raw header from `OpenIdConnect`, and rejects anything other than a bearer token; - **validates the token** against the provider: signature with the provider's published keys, issuer, audience and expiry; that work is covered with JWT validation; - **reads the granted scopes** from the validated claims; - **compares them** with the `SecurityScopes` it declares, raising `HTTPException` when a required scope is missing; - **never logs the raw header**, since it is a usable credential. Routes then depend on that wrapper through `Security(get_principal, scopes=[...])`, not on the scheme directly. ## The docs UI For the authorization-code scheme, Swagger UI at `/docs` sends the browser to `authorizationUrl`, exchanges the code at `tokenUrl`, and lands on the app's `swagger_ui_oauth2_redirect_url`, by default `/docs/oauth2-redirect`. Client settings for the UI go in `swagger_ui_init_oauth`. The provider has to accept that redirect address, or the login from the docs page fails before any FastAPI code runs. ## Common mistakes - **Depending on the scheme in routes.** `Depends(oidc_scheme)` hands the route a string any caller can type; only the validated wrapper's result should reach route code. - **Trusting the name.** A class called `OpenIdConnect` sounds like it speaks the protocol; it speaks only enough of OpenAPI to be drawn in the docs. - **Assuming the scopes dict restricts tokens.** On `OAuth2AuthorizationCodeBearer` it lists scopes for the docs dialog, exactly as on the password-flow class. - **Forgetting the provider can rotate keys.** A wrapper that pins one signing key breaks on rotation; fetching and caching the provider's key set is part of the validation work.

  • Why does it matter that OpenIdConnect returns the whole Authorization header?
    Code that passes the result straight to a token decoder receives `Bearer ...`, or a `Basic` credential, instead of a token. The wrapper must split the value, require the `Bearer` scheme and pass only the token on. Otherwise decoding fails in confusing ways, or a mistaken fallback treats a password credential as something else, and the raw value is easy to leak into logs.
  • What does /docs need to log in through an OAuth2AuthorizationCodeBearer scheme?
    The scheme's `authorizationUrl` and `tokenUrl` tell Swagger UI where to send the browser and where to exchange the code. The provider must accept the app's `swagger_ui_oauth2_redirect_url`, `/docs/oauth2-redirect` by default, as a redirect address, and settings such as a client id go in `swagger_ui_init_oauth`.

  • OpenIdConnect fetches the discovery document and validates tokens against it.
  • OAuth2AuthorizationCodeBearer checks the token's signature against tokenUrl.
  • OpenIdConnect strips the Bearer prefix like OAuth2PasswordBearer does.
  • Declaring scopes on OAuth2AuthorizationCodeBearer rejects tokens lacking them.
  • A route can depend on the scheme directly because the provider already checked the token.

Assumes FastAPI 0.143; since 0.122 the security classes answer a missing header with 401 and WWW-Authenticate instead of 403.