Lesson 32 of 59Identity and access
Log In with Google: OAuth 2 and OpenID Connect
How the authorization code flow with PKCE really works, how to add Google login to FastAPI with Authlib, and the token checks that stop account takeover.
The product team wants "Sign in with Google" by the end of the sprint, and a B2B customer is asking for login through their Okta. Both are OpenID Connect, built on OAuth 2. A library makes the happy path fifteen lines, which is exactly why teams ship it with holes: a missing state check, users matched by email, tokens accepted without checking who they were issued to. These bugs turn up in real penetration tests and bug bounty reports all the time. This lesson explains the protocol well enough that you can wire it up, review someone else's version, and answer the interview questions.
Four roles, two protocols
OAuth 2 names four parties. Using the right words makes design reviews much shorter.
- Resource owner: the user, who owns the data.
- Client: your application, which wants access. A confidential client runs on a server and can keep a
client_secret. A public client (an SPA, a mobile app) cannot, because anything shipped to a device can be extracted. - Authorization server: the service that logs the user in and issues tokens (Google, Okta, Auth0, Keycloak). Often called the identity provider (IdP).
- Resource server: the API that accepts access tokens. It could be Google's Calendar API, or your own API.
OAuth 2 is about delegated access: "let this app read my calendar". The client gets an access token with certain scopes (calendar.readonly), and the access token is meant for the resource server. OAuth on its own says nothing reliable about who the user is.
OpenID Connect (OIDC) adds identity on top. When the client asks for the openid scope, the authorization server also returns an ID token: a signed JWT that says who logged in (sub), who issued it (iss), which client it is for (aud), and when. There is also a userinfo endpoint that returns profile claims for an access token.
| Token | Who it is for | What it means | Format |
|---|---|---|---|
| ID token | Your client | "This user just logged in at this issuer" | Always a JWT |
| Access token | A resource server | "The bearer may do these scopes" | Often a JWT, sometimes opaque |
| Refresh token | The authorization server | "Give this client new access tokens" | Opaque; never send it to APIs |
The key rule from this table: log users in with the ID token, call APIs with the access token. Using an access token as proof of identity is a classic bug, because an access token issued to some other app can be replayed at yours.
The authorization code flow with PKCE
Every modern login uses one flow: authorization code with PKCE (Proof Key for Code Exchange, RFC 7636, said "pixie"). Walk through it step by step.
The user clicks the button. Your app generates three random values: state, nonce and a PKCE code_verifier, and saves them in a short-lived session.
The code travels through the browser (the front channel), where it can leak into logs, browser history, a malicious extension or a misconfigured redirect. That is fine, because the code alone is useless: redeeming it needs the code_verifier, which never left your server. The tokens only travel on the back channel.
state, nonce and PKCE: three different jobs
These three random values look alike and are often confused. Each stops a different attack.
stateties the callback to a login your app started in this browser. Without it, an attacker can start a login with their own Google account, stop before the callback, and trick the victim's browser into finishing it. The victim is now logged into the attacker's account (login CSRF) and may save a card or upload documents into it.noncegoes into the ID token. Checking it proves the ID token was minted for this login, not replayed from an earlier one.- PKCE proves that whoever redeems the code is whoever started the flow. A stolen code cannot be exchanged.
Press Run (⌘ Enter) to see what happens.The challenge is a one-way hash, so seeing it in the redirect URL does not reveal the verifier. The verifier must be 43 to 128 characters; token_urlsafe(32) gives 43.
Match each check to the attack it stops.
What is deprecated, and why the FastAPI tutorial looks different
RFC 9700, the OAuth 2.0 Security Best Current Practice (January 2025), collects a decade of attacks into rules:
- The implicit flow (
response_type=token, tokens returned in the URL fragment) should not be used. Tokens in URLs leak, and there is no way to bind them to the client. - The resource owner password credentials grant, where the app collects the user's password and sends it to the token endpoint, must not be used. It teaches users to type their password into any app and does not work with MFA or passkeys.
- PKCE is required for public clients and recommended for confidential ones. Use it everywhere.
- Redirect URIs are compared by exact string match.
- Refresh tokens for public clients must be sender-constrained or rotated.
OAuth 2.1 is an Internet-Draft that folds these rules into one spec: no implicit grant, no password grant, PKCE for every authorization code flow. It is still a draft, but providers already behave this way.
You may notice that the authentication lesson used OAuth2PasswordBearer and a /token endpoint that takes a username and password. That is FastAPI's tutorial pattern, and it is fine for a first-party app where the API itself owns the passwords: it is really "post a login form, get a bearer token", wearing OAuth names. What you must not do is build a third-party login on the password grant, or ask users for their Google password.
Google login in FastAPI with Authlib
Authlib is the most complete OAuth and OIDC client for Python, with a Starlette integration that FastAPI can use directly (uv add authlib httpx itsdangerous). It reads the provider's discovery document at /.well-known/openid-configuration, which lists the authorization and token endpoints, the JWKS URL and the supported algorithms, so you only configure a URL.
from authlib.integrations.starlette_client import OAuth, OAuthError
from fastapi import APIRouter, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from app.core.config import settings
oauth = OAuth()
oauth.register(
name="google",
server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
client_id=settings.google_client_id,
client_secret=settings.google_client_secret.get_secret_value(),
client_kwargs={"scope": "openid email profile", "code_challenge_method": "S256"},
)
router = APIRouter(prefix="/auth")
@router.get("/google/login")
async def google_login(request: Request):
redirect_uri = request.url_for("google_callback")
return await oauth.google.authorize_redirect(request, redirect_uri)
@router.get("/google/callback")
async def google_callback(request: Request, db: DB):
try:
token = await oauth.google.authorize_access_token(request)
except OAuthError:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "Login failed")
claims = token["userinfo"] # the validated ID token claims
user = find_or_create_user(db, issuer=claims["iss"], claims=claims)
response = RedirectResponse("/", status_code=303)
session_id = await create_session(user.id, request)
set_session_cookie(response, session_id)
return responseapp.add_middleware(
SessionMiddleware, secret_key=settings.session_secret.get_secret_value(),
https_only=True, max_age=600,
)
app.include_router(oidc.router)What Authlib does for you: authorize_redirect generates state, nonce (because the scope includes openid) and, with code_challenge_method set, the PKCE verifier, and stores them in request.session. That is why SessionMiddleware is required, and a signed cookie with a ten-minute lifetime is the right tool for it. authorize_access_token checks state, exchanges the code with the verifier, then validates the ID token against the provider's JWKS (signature, issuer, audience, expiry, nonce) and puts the claims in token["userinfo"]. A mismatched or missing state raises a subclass of OAuthError.
What it does not do: decide who the user is in your database, start your session, or decide what they may do. Those are yours.
Two deployment details cause most "works locally, fails in production" bugs. Behind a load balancer, request.url_for builds an http:// URL unless Uvicorn trusts the proxy headers (--forwarded-allow-ips), and the provider then rejects the redirect URI. And each environment needs its own registered redirect URI and usually its own client.
Linking the login to a local user
The ID token's sub is a stable, unique id for the user at that issuer. It never changes, even if the user changes their email. So the identity key is the pair (iss, sub):
CREATE TABLE identities (
id bigserial PRIMARY KEY,
user_id bigint NOT NULL REFERENCES users(id),
issuer text NOT NULL,
subject text NOT NULL,
email text,
created_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (issuer, subject)
);A separate identities table lets one user log in with Google and a password and Okta. Never match an incoming login to an existing account by email alone. Some providers let users set an email address they have not proven they own. If your app links on email, an attacker registers at such a provider with ceo@yourcustomer.com and walks into the CEO's account. Check email_verified is true before trusting the email for anything, and even then, link a new provider to an existing account only after the user proves they own that account (log in with the existing method first). Treat "is this the same person" as a security decision, not a convenience.
SELECT * FROM users WHERE email = :email_from_id_token. What is the risk?Validating tokens yourself
Sometimes there is no library callback to lean on: your API is a resource server that receives access tokens issued by your IdP (Auth0, Cognito, Keycloak) from a mobile app or another service. Then you validate each JWT yourself:
- Read the
kidfrom the token header and find that key in the issuer's JWKS (JSON Web Key Set), whose URL is in the discovery document. Cache the keys. Providers rotate them, so on an unknownkid, refetch once (with a rate limit), then fail. - Verify the signature with an algorithm allow-list that you choose, such as
["RS256"]or["ES256"]. Never trust the token's ownalg. Rejectnone, and never accept HS256 for a provider that signs with RSA. In an algorithm confusion attack, a token claimsHS256and is "signed" using the RSA public key as the HMAC secret, which a careless library would accept. - Check
issequals the expected issuer exactly,audcontains your API's identifier, andexpandnbfhold, with a small leeway for clock skew. - Check scopes or permissions for the specific endpoint.
Press Run (⌘ Enter) to see what happens.The last token is 30 seconds past exp but still accepted, because of the leeway. Keep leeway to a minute or two. In real code, PyJWT does all of this, and its PyJWKClient fetches and caches the JWKS (uv add "pyjwt[crypto]"):
import jwt
from fastapi import HTTPException, status
ISSUER = "https://your-tenant.example-idp.com/"
AUDIENCE = "https://api.example.com"
jwks = jwt.PyJWKClient(f"{ISSUER}.well-known/jwks.json", cache_keys=True)
def verify_access_token(token: str) -> dict:
try:
signing_key = jwks.get_signing_key_from_jwt(token)
return jwt.decode(
token, signing_key, algorithms=["RS256"],
audience=AUDIENCE, issuer=ISSUER,
options={"require": ["exp", "iss", "aud", "sub"]},
)
except jwt.PyJWTError:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid token",
headers={"WWW-Authenticate": "Bearer"})PyJWT rejects a token that has an aud claim when you pass no audience, and refuses to use an RSA public key as an HMAC secret, which are both safe defaults. get_signing_key_from_jwt makes a blocking HTTP call when the cache is cold, so in an async app call it in a thread or warm the cache at startup. Read the JWKS URL from the discovery document rather than guessing its path: it differs between providers.
Using check and good from the runnable block, what does this print?
print(check({"alg": "RS256"}, good, now=1_000_400, expected_nonce="n-9aa"))Machine to machine: client credentials
When a nightly billing job calls your API, there is no user and no browser. The client credentials grant fits: the job authenticates to the authorization server with its own client id and secret (or, better, a signed JWT assertion or mTLS) and receives a short-lived access token with the scopes that client was granted. Your API validates it like any other access token; the sub is the client, not a person.
How does that compare with an API key? An API key is a long-lived shared secret your API checks itself. It is simple and fine for customers calling your public API, as long as you store only a hash, show it once, support several keys per account so they can rotate, and scope each key. OAuth clients cost more to set up, but give you short-lived tokens, central revocation, standard scopes and one place to audit, which is why they win between internal services.
Build or buy
Running login yourself means password storage, resets, MFA, passkeys, account lockout, bot protection, enterprise SSO (SAML and OIDC for each customer's IdP) and audit logs. Hosted identity providers (Auth0 and Okta, Clerk, Amazon Cognito, Microsoft Entra ID) and self-hosted open-source ones (Keycloak, Zitadel, Authentik) do this for you. Most teams should buy or self-host one, and the deciding questions are enterprise SSO needs, data residency, and cost at your user count (check the vendors' current pricing pages).
What you still own either way: the local user and identity tables, your session or token handling, mapping claims to your users, and all of authorization. The IdP can tell you someone is ada@acme.com in the finance group. Whether she may approve invoice 812 is your code, which is the subject of the next lesson.
Order what your server does when the callback arrives.
- Tap the steps below in the right order.
- OpenID Connect (OIDC)
- An identity layer on OAuth 2 that adds the signed ID token, the
openidscope and the userinfo endpoint. - ID token
- A JWT for the client saying who logged in, at which issuer, for which audience, and when.
- PKCE
- Proof Key for Code Exchange: the client proves it started the flow by sending the verifier whose hash it sent earlier.
- state
- A random value that ties the callback to a login your app started in this browser, stopping login CSRF.
- JWKS
- JSON Web Key Set: the issuer's published public keys, picked by
kid, used to verify token signatures. - client credentials grant
- An OAuth flow for machine-to-machine calls where a client gets a token with its own credentials, without a user.
- RFC 9700
- The OAuth 2.0 Security Best Current Practice (2025), which deprecates the implicit and password grants.