← All cheatsheets

Security

OAuth 2.0, OIDC & JWT — flows, tokens, and validation

Fast-lookup reference for OAuth 2.0 roles and grants, OIDC ID vs access tokens, and JWT structure plus RS256/JWKS validation — built for debugging 401/403s and interview recall.

Docs-checkedoauthoidcjwtauthtokens

Quick reference — reach for these first

Decode a JWT (untrusted)python3 -c "import jwt,sys;print(jwt.get_unverified_header(sys.argv[1]));print(jwt.decode(sys.argv[1],options={'verify_signature':False}))" "$JWT"Read header {alg,kid} + claims WITHOUT trusting them — never authorize on an unverified token.
Verify with JWKS (RS256)python3 -c "import jwt;from jwt import PyJWKClient;k=PyJWKClient('$JWKS_URI').get_signing_key_from_jwt('$JWT').key;print(jwt.decode('$JWT',k,algorithms=['RS256'],audience='$AUD',issuer='$ISSUER'))"Fetch the kid's public key from JWKS and check signature + exp + aud + iss in one call.
Auth Code + PKCEverifier=rand; challenge=BASE64URL(SHA256(verifier)); /authorize?...&code_challenge=$challenge&code_challenge_method=S256 -> /token code+verifierBrowser-/mobile-/SPA-safe flow: challenge up front, verifier at token exchange. Replaces implicit & password.
Client credentials (M2M)curl -s -X POST https://AUTH_SERVER/token -d grant_type=client_credentials -d client_id=ID -d client_secret=SECRET -d scope=SCOPEMachine-to-machine; no user, no id_token, no refresh_token — just an access_token.
Check exp / aud / issjwt.decode(..., audience='$AUD', issuer='$ISSUER') # exp enforced automaticallyFour musts: valid signature, not expired (exp), right audience (aud), trusted issuer (iss).

Authorization Code flow with PKCE

Authorization Code flow with PKCEBrowser, client app, authorization server and resource API exchange a PKCE code challenge and verifier to obtain tokens, which the API validates against the JWKS.BrowserClient appAuth serverResource API1. verifier (random)challenge = S256(verifier)2. /authorize + code_challenge3. login + consent4. redirect ?code=AUTH_CODE5. POST /token code + verifier6. S256(verifier)== challenge?7. access + ID + refresh token8. GET /resource Bearer token9. verify sig via JWKS(kid, RS256);check exp/aud/iss

Text equivalent: Sequence across four lanes — Browser, Client app, Authorization server, Resource API. 1) The client generates a random verifier and a code_challenge = SHA-256(verifier). 2) The browser hits /authorize sending the code_challenge. 3) The authorization server runs login and consent. 4) It redirects back to the client with an authorization code. 5) The client posts the code plus the verifier to /token. 6) The server checks SHA-256(verifier) equals the stored challenge. 7) It returns access, ID, and refresh tokens. 8) The client calls the resource API with the Bearer access token. 9) The API verifies the signature via the JWKS using kid and RS256, and checks exp, aud, and iss.

Common tasks

Decode & verify · Auth Code + PKCE · M2M & OIDC

Decode & verifyAuth Code + PKCEM2M & OIDC
Decode a JWT header + payload (do NOT trust it yet)python3 -c "import jwt,sys;print(jwt.get_unverified_header(sys.argv[1]));print(jwt.decode(sys.argv[1],options={'verify_signature':False}))" "$JWT"Prints header {alg,kid} and claims; no signature check performed
Read kid + alg to locate the signing keypython3 -c "import jwt,sys;print(jwt.get_unverified_header(sys.argv[1]))" "$JWT"alg is RS256 (not none / HS256); note the kid value
Discover issuer endpoints + JWKS URIcurl -s $ISSUER/.well-known/openid-configuration | jq '{jwks_uri,token_endpoint,authorization_endpoint}'Returns an HTTPS jwks_uri plus token/authorize endpoints
Fetch the JWKS and find the key matching kidcurl -s $JWKS_URI | jq '.keys[] | select(.kid=="KID")'One key returned with kty RSA and matching kid
Verify signature + exp + aud + iss togetherpython3 -c "import jwt;from jwt import PyJWKClient;k=PyJWKClient('$JWKS_URI').get_signing_key_from_jwt('$JWT').key;print(jwt.decode('$JWT',k,algorithms=['RS256'],audience='$AUD',issuer='$ISSUER'))"Returns claims dict; raises on bad signature / exp / aud / iss
PKCE: generate a code_verifiercode_verifier=$(openssl rand -base64 32 | tr '/+' '_-' | tr -d '=')43-128 char URL-safe (base64url) string
PKCE: derive the S256 code_challengeprintf %s "$code_verifier" | openssl dgst -binary -sha256 | openssl base64 | tr '/+' '_-' | tr -d '='Base64url-encoded SHA-256 of the verifier
Open the /authorize request (code + PKCE)open "https://AUTH_SERVER/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&scope=openid%20profile&state=STATE&code_challenge=$code_challenge&code_challenge_method=S256"Login page loads; redirect returns ?code=&state= (state matches)
Exchange the code for tokens with the verifiercurl -s -X POST https://AUTH_SERVER/token -d grant_type=authorization_code -d code=AUTH_CODE -d redirect_uri=REDIRECT_URI -d client_id=CLIENT_ID -d code_verifier=$code_verifier | jqReturns access_token, id_token, refresh_token
M2M: get a client_credentials access tokencurl -s -X POST https://AUTH_SERVER/token -d grant_type=client_credentials -d client_id=CLIENT_ID -d client_secret=CLIENT_SECRET -d scope=SCOPE | jq -r .access_tokenReturns an access_token; NO id_token (there is no user)
Call the resource server with the access tokencurl -s -o /dev/null -w '%{http_code}\n' https://API/resource -H "Authorization: Bearer $ACCESS_TOKEN"200 = ok; 401 = token invalid/expired; 403 = scope/permission missing
OIDC: validate an ID token (aud = your client_id)python3 -c "import jwt;from jwt import PyJWKClient;k=PyJWKClient('$JWKS_URI').get_signing_key_from_jwt('$IDT').key;print(jwt.decode('$IDT',k,algorithms=['RS256'],audience='CLIENT_ID',issuer='$ISSUER'))"aud equals your client_id; sub identifies the signed-in user

A JWT is rejected with 401 — find out why and fix it

troubleshoot

1
Reproduce: call the API and capture the 401 plus any WWW-Authenticate detail
curl -i https://API/me -H "Authorization: Bearer $JWT"
# HTTP/1.1 401 Unauthorized
# WWW-Authenticate: Bearer error="invalid_token"
2
Decode header + payload WITHOUT trusting them (never authorize on an unverified JWT)
python3 -c "import jwt,sys;print(jwt.get_unverified_header(sys.argv[1]));print(jwt.decode(sys.argv[1],options={'verify_signature':False}))" "$JWT"
# {'alg':'RS256','kid':'abc123'}
# {'iss':'https://issuer/','aud':'api://default','exp':1731600000,'sub':'u_42'}
3
Check exp against now — expiry is the #1 cause
python3 -c "import time;print('now',int(time.time()))"
# now 1731603600  ->  exp 1731600000 is in the past = EXPIRED
4
If it were not expired, compare aud and iss to what the API enforces
5
Verify the signature against the issuer's JWKS (matches kid, pins RS256) to get the exact error
python3 -c "import jwt;from jwt import PyJWKClient;k=PyJWKClient('$ISSUER/.well-known/jwks.json').get_signing_key_from_jwt('$JWT').key;print(jwt.decode('$JWT',k,algorithms=['RS256'],audience='$AUD',issuer='$ISSUER'))"
# jwt.exceptions.ExpiredSignatureError: Signature has expired
6
Fix the cause — refresh the expired token (or re-request the correct audience/scope), then redeploy
curl -s -X POST $ISSUER/token -d grant_type=refresh_token -d refresh_token=$RT -d client_id=$CID | jq -r .access_token
7
Verify: re-call the API with the new token and confirm 200
curl -i https://API/me -H "Authorization: Bearer $NEW_JWT"
# HTTP/1.1 200 OK

Troubleshooting — symptom → first check → next check

SymptomFirst checkEstablishesNext check
401 invalid_token on a request that worked earlierDecode the payload and compare exp to the current epoch timeWhether the token is simply expired (the most common cause)Refresh via the refresh_token grant or re-authenticate; shorten the client-side refresh lead time
401 immediately after a token is issuedCompare the validator's clock to the token iat/nbf/expClock skew between issuer and validator (NTP drift)Sync clocks via NTP; allow a small leeway (e.g. 60s) in the validator
401 invalid_token with a valid, unexpired tokenCompare the token aud claim to the audience the API enforcesWrong audience — token was minted for a different API/resourceRequest the correct audience/scope at /token; configure the API's expected aud
Signature verification fails (InvalidSignature)Match the header kid against the keys in the current JWKSSigning key rotated, or wrong JWKS/issuer is being usedRefresh the cached JWKS (respect cache headers) and confirm you call the right issuer's jwks_uri
Tokens are accepted that should be rejectedConfirm the verifier pins algorithms=[RS256] and rejects alg=nonealg-confusion / alg=none flaw — an unverified JWT is being trustedAlways verify server-side, pin the expected algorithm, and never honor the token's own alg claim
403 (not 401) from the resource serverDecode the scope/scp or roles claim and compare to what the endpoint requiresAuthenticated but under-privileged — a scope/permission is missingRequest the needed scope at authorize/token; grant that permission to the client
Refresh fails with invalid_grant after working onceCheck whether refresh-token rotation is enabled and the prior token was reusedRotated refresh token — the previous refresh_token is now revokedStore and send the newest refresh_token from each response; treat reuse detection as a re-auth signal

References

Examples use PyJWT (Python) and standard curl/openssl so they run anywhere; a real deployment may use provider SDKs. CAPS tokens (AUTH_SERVER, CLIENT_ID, ISSUER, JWKS_URI, AUD, etc.) are placeholders. Verified against RFC 6749/7519/7636, RFC 9700, and OpenID Connect Core 1.0 (docs-checked); not executed in a sandbox. RS256 + JWKS is shown as the common asymmetric case.