Skip to content
Visual explainer 3h to learn 4 steps

OAuth 2.0 & OpenID Connect

Trace the authorization code flow with PKCE and say what each token is for.

By Invicly Tech, , in Cyber Security Fundamentals. About 11 minutes to read.

Topic 21 of 49

In short

OAuth 2.0 lets an app act on a user's behalf without their password by using tokens. OpenID Connect adds an identity layer with an ID token. The authorization code flow with PKCE is the recommended path for web and mobile apps.

Explained simply

Imagine a printing website that wants your photos from a cloud drive. In the old days, you would give it your password. Then it could do anything with your account, forever. OAuth 2.0 fixes this: the site gets a limited, temporary pass (a token) instead of your password.

OAuth has four roles. The resource owner is you. The client is the app asking for access. The authorization server logs you in and hands out tokens. The resource server is the API holding your data. You approve exactly what the app may do, such as "read photos".

OAuth is about permission, not about who you are. OpenID Connect (OIDC) is a thin layer on top that adds login. It gives the app an ID token that says who signed in. "Sign in with Google" or "Sign in with Microsoft" buttons use OIDC.

The recommended way for web, mobile and single-page apps is the authorization code flow with PKCE. The app gets a short-lived code, then swaps it for tokens over a direct back-channel. PKCE makes sure a stolen code is useless to anyone else.

Press Play on a diagram to walk through it one step at a time.

SequenceAuthorization code flow
User
App
Auth server
API
  1. 1Redirect to log in
    App to Auth server: Redirect to log in
  2. 2Authenticate and consent
    User to Auth server: Authenticate and consent
  3. 3Authorization code
    Auth server to App: Authorization code
  4. 4Exchange code for tokens
    App to Auth server: Exchange code for tokens
  5. 5Access and ID tokens
    Auth server to App: Access and ID tokens
  6. 6Call API with access token
    App to API: Call API with access token
MapWhich OAuth flow to use
OAuth 2.0 grant types
  • Authorization code + PKCE
    • Web apps
    • Single-page apps
    • Mobile and desktop apps
  • Client credentials
    • Service to service
    • No user involved
  • Device authorization
    • TVs and CLIs
    • User approves on another device
  • Refresh token
    • Renew access tokens
    • Rotate on every use
  • Avoid
    • Implicit flow
    • Resource owner password grant

In depth

The authorization request, parameter by parameter

The flow starts when the app sends your browser to the authorization server's /authorize endpoint. The URL carries several parameters. response_type=code asks for a code. client_id names the app. redirect_uri is where to send you back, and the server must compare it exactly with the registered value. scope lists the access requested, such as openid profile email or photos.read. state is a random value the app checks on return, which stops cross-site request forgery. nonce, for OIDC, is a random value that comes back inside the ID token to stop replay. code_challenge and code_challenge_method=S256 carry PKCE.

After you log in and consent, the server redirects to redirect_uri?code=...&state=.... The app then makes a direct POST to the /token endpoint with grant_type=authorization_code, the code, the redirect_uri and the code_verifier. A confidential client (a server-side app) also authenticates itself with its client secret or a signed assertion.

  • Exact redirect URI matching stops code theft via open redirects
  • state protects the redirect against CSRF
  • nonce binds the ID token to this login

PKCE: protecting the code

PKCE (Proof Key for Code Exchange, RFC 7636) was made for mobile apps, where another app on the phone could register the same custom URL scheme and receive the code. The fix: before redirecting, the app makes a random secret called the code_verifier (43 to 128 characters). It sends only a hash of it, the code_challenge = BASE64URL(SHA-256(code_verifier)), in the authorization request.

When the app later exchanges the code, it must send the original code_verifier. The server hashes it and compares it with the challenge it stored. An attacker who steals the code does not know the verifier, so the exchange fails.

The OAuth security best current practice (RFC 9700, published 2025) recommends PKCE for all clients, including server-side apps with a client secret, because it also stops code injection attacks. It also says not to use the old implicit flow or the password grant.

SequencePKCE stops a stolen code
App
Auth server
Attacker
  1. 1Authorize with code_challenge (hash)
    App to Auth server: Authorize with code_challenge (hash)
  2. 2Redirect with code
    Auth server to App: Redirect with code
  3. 3Tries stolen code, no verifier
    Attacker to Auth server: Tries stolen code, no verifier
  4. 4Rejected: invalid_grant
    Auth server to Attacker: Rejected: invalid_grant
  5. 5Code + code_verifier
    App to Auth server: Code + code_verifier
  6. 6Hash matches: tokens issued
    Auth server to App: Hash matches: tokens issued

Access, refresh and ID tokens

Each token has one audience and one job. The access token is for the API. It is short-lived (minutes to an hour) and carries scopes. It may be a JWT (JSON Web Token) the API validates itself, or an opaque string the API checks with the authorization server. The client should treat it as opaque.

The refresh token is for the authorization server only. The client uses it to get new access tokens without asking the user to log in again. It lives longer, so for browser and mobile apps servers should rotate it on every use and revoke the whole family if an old one is reused, which signals theft.

The ID token is for the client only. It is a signed JWT with claims such as iss (issuer), sub (stable user ID), aud (must equal your client_id), exp, iat and nonce. Validate the signature using the issuer's published keys (JWKS), then every claim. Never send the ID token to an API as an access token.

CompareThree tokens, three audiences
Access token
  • Sent to the API
  • Short-lived
  • Carries scopes
  • Bearer: whoever holds it can use it
Refresh token
  • Sent to the auth server only
  • Long-lived
  • Gets new access tokens
  • Rotate and revoke on reuse
ID token
  • Read by the client only
  • Signed JWT (OIDC)
  • Says who logged in
  • Check iss, aud, exp, nonce

Common mistakes and attacks to watch

Many OAuth incidents come from small validation gaps. Loose redirect URI matching (prefixes or wildcards) lets an attacker send codes to their own page. Not checking aud on an ID token lets a token issued to another app log someone in to yours. Accepting JWTs with alg none, or without checking the signature at all, lets anyone forge tokens. Storing tokens in browser localStorage exposes them to any XSS bug; a backend-for-frontend (BFF) that keeps tokens on the server and gives the browser a secure cookie is safer.

Attackers also abuse consent itself. In consent phishing, a victim is tricked into approving a malicious app that asks for scopes like reading mail. No password is stolen and MFA does not help, because the user really granted access. Defences: restrict which apps users can approve, require admin consent for sensitive scopes, review granted apps regularly, and alert on new apps with high-risk permissions.

  • Exact redirect URIs only
  • Validate signature, iss, aud, exp and nonce
  • Short access tokens; rotate refresh tokens
  • Review OAuth app grants in your tenant

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Explain OAuth roles~45m
  2. 2
    Trace the authorization code flow~45m
  3. 3
    Explain PKCE and why it matters~45m
  4. 4
    Compare access, refresh and ID tokens~45m

Key points

  • OAuth delegates access without sharing the password.
  • OIDC adds an ID token describing the user.
  • PKCE protects the code exchange from interception.
  • Access tokens are short-lived; refresh tokens renew them.

Key terms

Tap a card to flip it. 0/4 known

Examples

Making a PKCE pair and the authorization URL

Step 1: create a high-entropy code_verifier with the secrets module. Step 2: hash it with SHA-256 and Base64url-encode it without padding to get the code_challenge. Step 3: create random state and nonce values and keep them, with the verifier, in the user's server-side session. Step 4: build the authorization URL. Step 5: when the browser returns, check state first, then exchange the code with the stored code_verifier.

python
import base64, hashlib, secrets
from urllib.parse import urlencode

verifier = secrets.token_urlsafe(48)                      # 64 chars
challenge = base64.urlsafe_b64encode(
    hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
state, nonce = secrets.token_urlsafe(16), secrets.token_urlsafe(16)

params = {"response_type": "code", "client_id": "my-app",
          "redirect_uri": "https://app.example.com/callback",
          "scope": "openid profile email", "state": state, "nonce": nonce,
          "code_challenge": challenge, "code_challenge_method": "S256"}
print("https://login.example.com/authorize?" + urlencode(params))

Reading and validating an ID token

A JWT is three Base64url parts separated by dots: header, payload and signature. Step 1: decode the header and payload to look at them (this is for debugging only; decoding is not validation). Step 2: in real code, use a library such as PyJWT with the issuer's JWKS URL to check the signature. Step 3: require the expected algorithm, issuer and audience. Step 4: compare the nonce claim with the one stored in the session. If any check fails, reject the login.

python
import jwt   # PyJWT

jwks = jwt.PyJWKClient("https://login.example.com/.well-known/jwks.json")

def validate_id_token(id_token: str, expected_nonce: str) -> dict:
    key = jwks.get_signing_key_from_jwt(id_token)
    claims = jwt.decode(id_token, key.key, algorithms=["RS256"],
                        audience="my-app", issuer="https://login.example.com")
    if claims.get("nonce") != expected_nonce:
        raise ValueError("nonce mismatch")
    return claims   # claims["sub"] is the stable user ID

Quick reference

  • OAuth = delegated access (authorization); OIDC = login (authentication) on top of OAuth
  • Use authorization code + PKCE for every client; avoid implicit and password grants
  • code_challenge = BASE64URL(SHA256(code_verifier)), method S256
  • Access token goes to the API; refresh token to the auth server; ID token stays with the client
  • Validate ID tokens: signature (JWKS), iss, aud = your client_id, exp, nonce
  • Register exact redirect URIs; never allow wildcards
  • Client credentials grant is for machine-to-machine calls with no user
  • Review consented OAuth apps; require admin consent for high-risk scopes

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What is the purpose of the state parameter?

Question 2

2Which token should a client send to a resource API?

Question 3

3An attacker steals an authorization code from a redirect. Why can't they exchange it when PKCE is used?

Question 4

4A user approves a malicious app that requests permission to read their mailbox. Why does MFA not help?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Decode the payload of any JWT (for example one from jwt.io's sample) without a library and list its claims.

  2. Exercise 2medium

    Look up the OpenID configuration of a real provider and find its authorization, token and JWKS endpoints and the signing algorithms it supports.

  3. Exercise 3hard

    Review this app config and list every security problem: implicit flow for a SPA, redirect URIs https://app.example.com/*, access token stored in localStorage, refresh tokens valid 1 year with no rotation, ID token sent to the API as a bearer token.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is OAuth an authentication protocol?
No. OAuth is for delegated authorization: giving an app access to an API. OpenID Connect adds authentication on top, with the ID token describing who logged in.
What is the difference between a JWT and an access token?
JWT is a token format: signed JSON. An access token is a role. Access tokens are often JWTs, but they can also be random opaque strings the API checks with the authorization server.
Do I still need PKCE if my app has a client secret?
Yes. Current best practice (RFC 9700) recommends PKCE for all clients, because it also prevents code injection attacks that a client secret does not stop.
Where should a browser app store tokens?
Ideally not in the browser at all: a backend-for-frontend keeps tokens on the server and uses a secure, HttpOnly cookie. If tokens must be in the browser, keep them in memory and short-lived, not in localStorage.

Go deeper

ShareXLinkedInWhatsApp