Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 80 ยท Authentication and Access Control

OAuth 2.0, OpenID Connect and SSO

Understand OAuth 2.0 roles, the authorization code flow with PKCE, scopes, the state parameter, OpenID Connect and SSO, and the misconfigurations that cause breaches.

You have probably clicked "Sign in with Google" or approved an app to "access your calendar". Behind those buttons are OAuth 2.0, a framework for delegated authorization, and OpenID Connect (OIDC), a thin layer on top that adds authentication. Together they let a user prove who they are, or grant limited access to their data, without ever giving a password to the third-party app.

The same machinery powers enterprise single sign-on (SSO): sign in once to your company's identity provider and open dozens of apps without logging in again. Getting these flows wrong leads to account takeover, which is why OAuth is one of the most common sources of serious login bugs. In this lesson you will learn the roles, follow the authorization code flow with PKCE, see how the state parameter and exact redirect matching stop attacks, and run a small simulation. Tokens themselves are covered in Sessions, Cookies and JWTs.

OAuth is authorization, not authentication

OAuth 2.0 answers "may this app act on the user's behalf, within these limits?" It hands the app an access token. It does not, by itself, tell the app who the user is. Treating an access token as proof of identity is a classic mistake. OpenID Connect fixes this by adding an ID token (a signed JWT that says who authenticated, when and for which app) and a standard /userinfo endpoint.

The four roles

  • Resource owner: the user who owns the data.
  • Client: the application that wants access (a web app, a mobile app, a script).
  • Authorization server: authenticates the user, asks for consent and issues tokens (the login page of your identity provider).
  • Resource server: the API that holds the data and accepts access tokens.

Clients are confidential (can keep a secret, like a server-side web app) or public (cannot, like a mobile app or single-page app). Public clients must never rely on a client secret, because anyone can extract it.

The authorization code flow with PKCE

Today's recommended flow for almost every client is the authorization code flow with PKCE ("pixie", Proof Key for Code Exchange). The older implicit flow, which returned tokens directly in the URL, and the resource owner password flow, where the app collected the user's password, are discouraged in current best practice (the OAuth 2.1 draft removes them).

sequenceDiagram
    participant U as User (browser)
    participant C as Client app
    participant A as Authorization server
    participant R as Resource server (API)
    C->>C: create code_verifier (random) and code_challenge = SHA-256(verifier)
    C->>U: redirect to /authorize with client_id, redirect_uri, scope, state, code_challenge
    U->>A: user logs in and approves the scopes
    A->>U: redirect to redirect_uri with code and state
    U->>C: browser delivers code and state
    C->>C: check state equals the value it stored
    C->>A: POST /token with code, redirect_uri, code_verifier
    A->>A: check SHA-256(verifier) equals the stored challenge
    A-->>C: access token (and ID token, refresh token)
    C->>R: API call with Authorization: Bearer access_token

The browser only ever carries a short-lived code. The tokens travel on a direct, back-channel request that needs the secret verifier.

Each parameter has a purpose:

  • client_id identifies the app. redirect_uri says where the code is sent and must match one the app registered in advance.
  • scope lists the access requested (openid email, calendar.read). Grant the least privilege needed, and show the user clearly what they are approving.
  • state is a random value the client generates and checks when the user comes back. It ties the response to the request and stops login CSRF, where an attacker makes a victim's browser finish the attacker's authorization and thereby links the attacker's account to the victim.
  • code_challenge is BASE64URL(SHA-256(code_verifier)). The verifier is revealed only in the token request. A stolen authorization code (from a log, a referrer header, or a malicious app that registered the same custom URL scheme) is useless without it.
  • nonce (OIDC) is bound into the ID token to stop replay of an ID token into a different login.

Computing a PKCE challenge

PKCE uses only a hash. This demo follows the official test vector from RFC 7636, then generates a fresh pair the way a client does:

Python PKCE verifier and challenge

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A mini authorization server (simulation)

The simulation below plays all roles in one script, with no network. It registers a client, issues a single-use code bound to the PKCE challenge, and then lets an attacker try to redeem a stolen code.

Python Authorization code flow with PKCE, simulated

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Redirect URI validation

The authorization server must compare the requested redirect_uri against the registered list using exact string matching. Looser rules are a repeating source of account takeovers: if the check is "starts with", "contains" or allows wildcards, an attacker registers a look-alike address or finds an open redirect on a trusted domain and receives the victim's code or token.

Python Why prefix matching is dangerous

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

OpenID Connect and the ID token

When the scope includes openid, the token response contains an ID token: a JWT signed by the identity provider. The client must validate it before trusting any identity claim:

  1. Verify the signature with the provider's published keys (its JWKS), pinning the algorithm, as discussed in the previous lesson.
  2. Check iss equals the expected provider, aud contains your client_id, and exp has not passed.
  3. Check that nonce equals the value sent in the request.
  4. Identify the user by the pair (iss, sub), not by email. The sub value is stable and unique per issuer, while emails change and, with some providers, are unverified.

Never use an ID token as an API access token and never accept an access token as proof of login. They have different audiences and purposes.

SSO and federation

In SAML or OIDC single sign-on, an identity provider (IdP) such as Okta, Microsoft Entra ID or Keycloak authenticates the user once, and many service providers (SPs) trust its assertions. Benefits: central MFA, central offboarding (disable one account, lose access everywhere), and fewer passwords. Risks: the IdP becomes a single point of failure and a prime target, so protect it with strong MFA (Multi-Factor Authentication and Passkeys), monitor it, and keep session lifetimes sensible.

Common OAuth misconfigurations

  • Loose redirect_uri matching (wildcards, prefixes, open redirects on the same domain).
  • Missing or unchecked state, enabling login CSRF and account linking attacks.
  • No PKCE on public clients, or on any client that can use it.
  • Implicit flow or tokens in URLs, which leak through history, logs and Referer headers.
  • Over-broad scopes and long-lived access tokens; refresh tokens that are not rotated.
  • Trusting an unverified email claim to merge accounts, letting an attacker claim someone else's address at a weak provider.
  • Client secrets in mobile apps, JavaScript or repositories (Randomness, Key Management and Secrets).
  • Skipping aud/iss checks, which allows tokens from another app or tenant to be accepted.
  • Consent phishing, where a malicious app tricks users into approving powerful scopes. Restrict who may register apps and require admin consent for risky scopes.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main difference between OAuth 2.0 and OpenID Connect?

    OAuth 2.0 issues access tokens to act on a user's behalf. OpenID Connect builds on it with an ID token and standard claims that tell the client who authenticated.
  2. 2. What attack does the state parameter mainly prevent?

    The client stores a random state and checks it on return, ensuring the response belongs to a request it started.
  3. 3. What does PKCE protect against?

    The authorization server stores the hash of the verifier and requires the original when the code is redeemed, so an intercepted code alone is worthless.
  4. 4. How should an authorization server validate redirect_uri?

    Prefix and wildcard rules enable look-alike domains and open-redirect chains that deliver the code to an attacker.
  5. 5. Which identifier should your app use as the stable key for a user signing in with OIDC?

    sub is unique and stable per issuer; emails can change or be unverified. Combining it with iss avoids collisions across providers.

Summary

  • OAuth 2.0 delegates access with scoped tokens; OpenID Connect adds identity through a signed ID token; SSO centralizes login at an identity provider.
  • Use the authorization code flow with PKCE, a random state, and nonce for OIDC; avoid the implicit and password flows.
  • Match redirect_uri exactly, request the least scope, and keep codes single-use and short-lived.
  • Validate ID tokens (signature, iss, aud, exp, nonce) and identify users by iss plus sub.
  • Protect client secrets, rotate refresh tokens and defend the identity provider with strong MFA and monitoring.

Next: Authorization and Access Control Models, which covers what a user may do once they are in.