Skip to content

Authorization Code with PKCE — Secure OAuth Flow for Mobile and SPA

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Authorization Code Pkce. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

PKCE extends the Authorization Code flow with a dynamically generated proof key that prevents authorization code interception attacks.

// PKCE flow in a SPA
async function loginWithPKCE() {
  // Step 1: Generate code verifier and challenge
  const codeVerifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
  const codeChallenge = base64url(
    await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier))
  );

  // Store verifier for callback
  sessionStorage.setItem('code_verifier', codeVerifier);

  // Step 2: Redirect to authorization endpoint
  const params = new URLSearchParams({
    response_type: 'code',
    client_id: 'spa-client',
    redirect_uri: 'https://app.example.com/callback',
    code_challenge: codeChallenge,
    code_challenge_method: 'S256',
    scope: 'openid profile email scan:read',
    state: crypto.randomUUID()
  });

  sessionStorage.setItem('oauth_state', params.get('state'));
  window.location.href = `https://auth.example.com/authorize?${params}`;
}

// Step 3: Exchange code for tokens
app.get('/callback', async (req, res) => {
  const { code, state } = req.query;
  const storedState = sessionStorage.getItem('oauth_state');
  if (state !== storedState) throw new Error('State mismatch');

  const codeVerifier = sessionStorage.getItem('code_verifier');
  const response = await axios.post('https://auth.example.com/oauth/token', {
    grant_type: 'authorization_code',
    client_id: 'spa-client',
    code,
    code_verifier: codeVerifier,
    redirect_uri: 'https://app.example.com/callback'
  });

  const { access_token, refresh_token } = response.data;
});

PKCE provides the highest level of security for public clients without client secrets.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro