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.
Quick reference — reach for these first
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.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.verifier=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.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.jwt.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
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 & verify | Auth Code + PKCE | M2M & 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 key | python3 -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 URI | curl -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 kid | curl -s $JWKS_URI | jq '.keys[] | select(.kid=="KID")' | One key returned with kty RSA and matching kid |
| Verify signature + exp + aud + iss together | 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'))" | Returns claims dict; raises on bad signature / exp / aud / iss |
| PKCE: generate a code_verifier | code_verifier=$(openssl rand -base64 32 | tr '/+' '_-' | tr -d '=') | 43-128 char URL-safe (base64url) string |
| PKCE: derive the S256 code_challenge | printf %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 verifier | curl -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 | jq | Returns access_token, id_token, refresh_token |
| M2M: get a client_credentials access token | curl -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_token | Returns an access_token; NO id_token (there is no user) |
| Call the resource server with the access token | curl -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
curl -i https://API/me -H "Authorization: Bearer $JWT"
# HTTP/1.1 401 Unauthorized
# WWW-Authenticate: Bearer error="invalid_token"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'}python3 -c "import time;print('now',int(time.time()))"
# now 1731603600 -> exp 1731600000 is in the past = EXPIREDpython3 -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 expiredcurl -s -X POST $ISSUER/token -d grant_type=refresh_token -d refresh_token=$RT -d client_id=$CID | jq -r .access_token
curl -i https://API/me -H "Authorization: Bearer $NEW_JWT"
# HTTP/1.1 200 OKTroubleshooting — symptom → first check → next check
| Symptom | First check | Establishes | Next check |
|---|---|---|---|
| 401 invalid_token on a request that worked earlier | Decode the payload and compare exp to the current epoch time | Whether 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 issued | Compare the validator's clock to the token iat/nbf/exp | Clock 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 token | Compare the token aud claim to the audience the API enforces | Wrong audience — token was minted for a different API/resource | Request 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 JWKS | Signing key rotated, or wrong JWKS/issuer is being used | Refresh the cached JWKS (respect cache headers) and confirm you call the right issuer's jwks_uri |
| Tokens are accepted that should be rejected | Confirm the verifier pins algorithms=[RS256] and rejects alg=none | alg-confusion / alg=none flaw — an unverified JWT is being trusted | Always verify server-side, pin the expected algorithm, and never honor the token's own alg claim |
| 403 (not 401) from the resource server | Decode the scope/scp or roles claim and compare to what the endpoint requires | Authenticated but under-privileged — a scope/permission is missing | Request the needed scope at authorize/token; grant that permission to the client |
| Refresh fails with invalid_grant after working once | Check whether refresh-token rotation is enabled and the prior token was reused | Rotated refresh token — the previous refresh_token is now revoked | Store and send the newest refresh_token from each response; treat reuse detection as a re-auth signal |
References
- RFC 6749 — The OAuth 2.0 Authorization Frameworkdatatracker.ietf.org
- RFC 7519 — JSON Web Token (JWT)datatracker.ietf.org
- RFC 7636 — Proof Key for Code Exchange (PKCE)datatracker.ietf.org
- OpenID Connect Core 1.0openid.net
- RFC 9700 — OAuth 2.0 Security Best Current Practicedatatracker.ietf.org
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.