Skip to main content

PKCE Flow

Overview

The PKCE (Proof Key for Code Exchange) Flow is an enhanced version of the Authorization Code Flow designed to improve security, especially for public clients like mobile applications or single-page apps (SPAs) that cannot securely store a client secret. During the token exchange, PKCE mitigates the risk of authorization code interception using a dynamic, cryptographically secure mechanism (the code verifier and code challenge). This flow is widely recommended for public clients to ensure robust security when interacting with OpenID Connect (OIDC) providers like LoginRadius.

Steps to Implement PKCE Flow

  1. Generate Code Verifier and Code Challenge

    • Code Verifier: A random, high-entropy string.
    • Code Challenge: A BASE64-URL-encoded SHA256 hash of the code verifier.

    Example in JavaScript:

const crypto = require('crypto');
const codeVerifier = crypto.randomBytes(32).toString('base64url');
const codeChallenge = crypto.createHash('sha256').update(codeVerifier).digest('base64url');
  1. Initiate Authorization Request

    Redirect users to the authorization endpoint:

https://<siteurl>/service/oidc/{oidcAppName}/authorize?client_id={OIDC Client ID}&redirect_uri={Callback URL}&scope=openid&response_type=code&state={random long string}&code_challenge={code challenge}&code_challenge_method=S256
  1. Receive Authorization Code

    After user authentication, the server redirects to the redirect_uri with the authorization code:

REDIRECT_URI?code={authorization code}&state={original state value}
  1. Exchange Authorization Code for Tokens

    Make a POST request to the token endpoint:

POST https://<siteurl>/api/oidc/{oidcAppName}/token

Request Body:

{
"client_id": "<OIDC Client ID>",
"redirect_uri": "<Callback URL>",
"grant_type": "authorization_code",
"code": "<authorization code>",
"code_verifier": "<code verifier>"
}

Response:

{
"access_token": "<token>",
"id_token": "<id token>",
"refresh_token": "<refresh token>",
"expires_in": <seconds>
}

The PKCE Flow provides a strong layer of security for public clients, such as mobile apps or SPAs that cannot safely store client secrets. By introducing the code verifier and code challenge mechanism, PKCE ensures that intercepted authorization codes cannot be used maliciously. This makes the flow ideal for applications that protect sensitive data and provide secure resource access. By following the steps outlined above, developers can seamlessly integrate PKCE-based authentication into their applications with LoginRadius and benefit from enhanced security in the OIDC protocol.