Skip to main content

How to Implement OAuth2 and OIDC Login

Add OIDC login to a web app using the Authorization Code flow with PKCE: register a client, run the redirect flow, exchange the code, validate the ID token, and create a secure session.

Difficulty
Intermediate
Duration
50 minutes
Steps
6

What and why

OAuth2 is an authorization framework; OpenID Connect (OIDC) adds an identity layer on top so you also learn who the user is via an ID token. The Authorization Code flow with PKCE (Proof Key for Code Exchange) is the recommended flow for web and native apps because it never exposes long-lived secrets in the browser.

Prerequisites

  • A web application with server-side routes.
  • An OIDC provider: Keycloak, Auth0, or similar.
  • HTTPS for redirect URIs (localhost is allowed in development).

Steps

1. Register an OIDC client

In your provider, create a client (application). Set the redirect URI to https://app.example.com/callback, choose the Authorization Code grant, and note the client ID. Keep a client secret if your backend is confidential.

2. Build the authorization request with PKCE

Generate a code verifier and its SHA-256 challenge, then redirect the user:

const verifier = base64url(crypto.randomBytes(32));
const challenge = base64url(crypto.createHash('sha256').update(verifier).digest());
// store verifier and a random state in the session
res.redirect(`${authEndpoint}?response_type=code&client_id=${id}` +
  `&redirect_uri=${redirect}&scope=openid%20profile%20email` +
  `&state=${state}&code_challenge=${challenge}&code_challenge_method=S256`);

3. Handle the redirect callback

At /callback, verify the returned state matches the stored value to defend against CSRF, then read the code.

4. Exchange the code for tokens

const body = new URLSearchParams({
  grant_type: 'authorization_code', code, redirect_uri: redirect,
  client_id: id, code_verifier: verifier,
});
const tokens = await fetch(tokenEndpoint, { method: 'POST', body }).then(r => r.json());

You receive an access token, an ID token, and often a refresh token.

5. Validate the ID token

The ID token is a JWT. Verify its signature against the provider's JWKS, and check iss, aud, exp, and the nonce if you sent one. Use a library such as jose rather than hand-rolling validation.

6. Create a session and log out

After validation, create your own session cookie (HttpOnly, Secure, SameSite). For logout, clear the cookie and redirect to the provider's end-session endpoint.

Verification

  • The login redirect lands on the provider and back to your callback.
  • Token exchange returns an ID token that passes signature and claim checks.
  • A protected route is accessible only after login.

Next Steps

Use refresh tokens to extend sessions, request the minimal scopes you need, and map provider claims to roles for authorization. For APIs, validate the access token as a bearer credential.

Prerequisites

  • A web application
  • An OIDC provider account or Keycloak
  • HTTPS for redirect URIs

Steps

  • 1
    Register an OIDC client
  • 2
    Build the authorization request with PKCE
  • 3
    Handle the redirect callback
  • 4
    Exchange the code for tokens
  • 5
    Validate the ID token
  • 6
    Create a session and log out