DEV Community

Michay Kalika
Michay Kalika

Posted on Edited on Originally published at frontegg.com

OAuth flows explained: which flow to use for web apps, SPAs, mobile, devices and services

Use authorization code with PKCE for anything a person signs in to: server-rendered web apps, SPAs, and mobile or desktop apps. Use client credentials when a service calls an API as itself, and the device authorization flow for TVs, CLIs and other devices where typing is painful. Implicit and resource owner password (ROPC) are legacy, and RFC 9700 tells you to stop using them.

That's the whole decision. The rest of this post shows the raw requests and some small Node.js code for each flow, so you can see what your library is doing for you.

Disclosure: I work at Frontegg. The examples use standard OAuth 2.0 and work with any authorization server.

The which-flow table

App type Flow Why
Server-side web app Authorization code + PKCE Secret stays on the server; PKCE is still recommended
SPA Authorization code + PKCE Can't keep a secret; PKCE makes a stolen code useless
Native mobile / desktop Authorization code + PKCE Same as SPA
Backend job, service, API integration (no user) Client credentials The app is the resource owner
TV, console, CLI, IoT Device authorization (RFC 8628) User approves on a phone or laptop
Legacy app that collects passwords ROPC: avoid RFC 9700 §2.4: "MUST NOT be used"
Browser app on implicit Implicit: avoid RFC 9700 §2.1.2: clients "SHOULD NOT use" it

Two RFC 9700 rules decide most of this table. Public clients MUST use PKCE, and confidential clients are RECOMMENDED to (§2.1.1). Refresh tokens issued to public clients MUST be sender-constrained or rotated (§2.2.2).

If you want the longer conceptual walkthrough (roles, the hybrid flow, a step-by-step of each grant), the full OAuth flows guide covers it. Here we stay close to the wire.

1. Authorization code + PKCE

PKCE (RFC 7636) has the client make up a random code_verifier and send only its SHA-256 hash, the code_challenge, on the authorization request. When it exchanges the code, it sends the verifier, so a stolen code can't be redeemed without it.

// pkce.js
import { randomBytes, createHash } from "node:crypto";

// RFC 7636 §4.1: 43-128 chars from [A-Za-z0-9-._~]. 32 random bytes -> 43 base64url chars.
export function createVerifier() {
  return randomBytes(32).toString("base64url");
}

// RFC 7636 §4.2: code_challenge = BASE64URL(SHA256(ASCII(code_verifier)))
export function createChallenge(verifier) {
  return createHash("sha256").update(verifier, "ascii").digest("base64url");
}
Enter fullscreen mode Exit fullscreen mode

Build the authorization URL and keep the verifier and state until the callback:

// authorize-url.js
import { randomBytes } from "node:crypto";
import { createVerifier, createChallenge } from "./pkce.js";

export function buildAuthorizeUrl({ authorizeEndpoint, clientId, redirectUri, scope }) {
  const verifier = createVerifier();
  const state = randomBytes(16).toString("base64url");
  const url = new URL(authorizeEndpoint);
  url.search = new URLSearchParams({
    response_type: "code",
    client_id: clientId,
    redirect_uri: redirectUri,
    scope,
    state,
    code_challenge: createChallenge(verifier),
    code_challenge_method: "S256",
  });
  // Store verifier + state server-side (or in session storage for a SPA) until the callback.
  return { url: url.toString(), verifier, state };
}
Enter fullscreen mode Exit fullscreen mode

On the callback, check that state matches, then exchange the code:

// exchange-code.js
export async function exchangeCode({ tokenEndpoint, clientId, redirectUri, code, verifier }) {
  const res = await fetch(tokenEndpoint, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({
      grant_type: "authorization_code",
      code,
      redirect_uri: redirectUri,
      client_id: clientId,
      code_verifier: verifier,
    }),
  });
  if (!res.ok) throw new Error(`token exchange failed: ${res.status} ${await res.text()}`);
  return res.json();
}
Enter fullscreen mode Exit fullscreen mode

Always use S256. The plain method puts the verifier itself in the URL, and RFC 9700 says S256 is currently the only method that doesn't expose it.

A server-side web app does the same thing and also authenticates with its client secret. PKCE doesn't replace the secret; it adds a second check.

2. Client credentials (no user)

// client-credentials.js
export async function getServiceToken({ tokenEndpoint, clientId, clientSecret, scope }) {
  const res = await fetch(tokenEndpoint, {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
      // RFC 6749 §2.3.1: HTTP Basic with the form-urlencoded client_id and secret
      Authorization:
        "Basic " +
        Buffer.from(
          `${encodeURIComponent(clientId)}:${encodeURIComponent(clientSecret)}`
        ).toString("base64"),
    },
    body: new URLSearchParams({ grant_type: "client_credentials", scope }),
  });
  if (!res.ok) throw new Error(`client_credentials failed: ${res.status} ${await res.text()}`);
  return res.json(); // { access_token, token_type, expires_in } and no refresh_token
}
Enter fullscreen mode Exit fullscreen mode

Two things people trip on. RFC 6749 says to form-urlencode the client ID and secret before they go into the Basic header. Skip that and a client ID containing :, or a secret containing % or +, can be misread by the server. And RFC 6749 §4.4.3 says this grant shouldn't return a refresh token, so cache the access token until shortly before expires_in and request a new one.

3. Device authorization (RFC 8628)

The device asks for a code, shows the user a short user_code and a URL, and polls the token endpoint until the user approves on another device. The polling rules are easy to get wrong, so here they are in code:

// device-flow.js
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export async function deviceLogin({ deviceEndpoint, tokenEndpoint, clientId, scope, show }) {
  // 1. Ask for a device code (RFC 8628 §3.1)
  const start = await fetch(deviceEndpoint, {
    method: "POST",
    headers: { "Content-Type": "application/x-www-form-urlencoded" },
    body: new URLSearchParams({ client_id: clientId, scope }),
  });
  if (!start.ok) throw new Error(`device authorization failed: ${start.status}`);
  const { device_code, user_code, verification_uri, expires_in, interval = 5 } =
    await start.json();

  // 2. Tell the user where to go and what to type
  show({ user_code, verification_uri });

  // 3. Poll the token endpoint (RFC 8628 §3.4-3.5)
  let wait = interval;
  const deadline = Date.now() + expires_in * 1000;
  while (Date.now() < deadline) {
    await sleep(wait * 1000);
    const res = await fetch(tokenEndpoint, {
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: new URLSearchParams({
        grant_type: "urn:ietf:params:oauth:grant-type:device_code",
        device_code,
        client_id: clientId,
      }),
    });
    const body = await res.json().catch(() => ({ error: `http_${res.status}` }));
    if (res.ok) return body; // access_token, maybe refresh_token
    if (body.error === "authorization_pending") continue;
    if (body.error === "slow_down") { wait += 5; continue; } // +5s for this and all later polls
    throw new Error(`device login failed: ${body.error}`); // access_denied, expired_token, ...
  }
  throw new Error("device login timed out");
}
Enter fullscreen mode Exit fullscreen mode

The rules this follows, from RFC 8628:

  • If the server sends no interval, the default is 5 seconds.
  • authorization_pending: wait, then poll again.
  • slow_down: add 5 seconds to the interval, and keep it for every later poll.
  • access_denied or expired_token: stop.

4. The two flows to retire

  • Implicit (response_type=token) puts the access token in the redirect URL, where it can leak through browser history and logs. Move SPAs to authorization code + PKCE.
  • ROPC has your app handle the user's password directly, which makes MFA, SSO and passkeys at the identity provider hard or impossible to use. Move to authorization code + PKCE, even for first-party apps.

The OAuth 2.1 draft drops both grants and requires PKCE for authorization code.

Doing this with Frontegg

If you use Frontegg as the authorization server, the flows above map like this:

  • Hosted login supports authorization code with PKCE at /oauth/authorize on your Frontegg domain (docs).
  • Device flow: point deviceEndpoint at https://{your-domain}/frontegg/oauth/device/authorize and tokenEndpoint at https://{your-domain}/frontegg/oauth/token. The grant type and the authorization_pending / slow_down handling are the same as above (docs).
  • One difference to know about: you host the verification page yourself. In the code above, show the user your own page URL (for example https://app.example.com/device-activate?user_code=...), not the verification_uri or verification_uri_complete from the response (and don't put them in a QR code). The docs say those URIs point to a JSON API. Your page signs the user in, calls GET /frontegg/oauth/device?user_code=... to show the app name and scopes, then calls POST /frontegg/oauth/device/verify with the user's approve or deny decision.

Endpoints are also listed in the OIDC discovery document at https://{your-domain}/.well-known/openid-configuration.

Checklist

  • [ ] Every user sign-in uses authorization code + PKCE with S256
  • [ ] state is random and checked on the callback
  • [ ] Confidential clients still send their secret; PKCE is in addition to it
  • [ ] Service-to-service calls use client credentials and cache the token until near expires_in
  • [ ] Device clients respect interval, add 5s on slow_down, and stop on any other error (access_denied, expired_token, ...)
  • [ ] Public-client refresh tokens are rotated or sender-constrained
  • [ ] No implicit, no ROPC

Tested with Node.js 22.23.4 against a local mock authorization server, including the RFC 7636 Appendix B PKCE test vector. For the conceptual background behind the table, see the OAuth flows guide on frontegg.com.

Top comments (0)