OAuth2 | Authorization Code with PKCE (RFC 7636)

Overview

The Authorization Code with PKCE (Proof Key for Code Exchange) grant extends the standard Authorization Code flow with an additional security layer. It is designed for native applications, mobile applications, and single-page applications (SPAs) where the client secret cannot be stored securely. Instead of relying on a client secret, the client generates a cryptographic code verifier and challenge that prove the entity exchanging the authorization code is the same entity that initiated the flow.

How PKCE Works

  1. Client generates a random code_verifier (32 bytes of cryptographically random data, Base64URL encoded).
  2. Client computes the code_challenge as the SHA-256 hash of the code_verifier, Base64URL encoded.
  3. Client sends the code_challenge and code_challenge_method=S256 with the authorization request.
  4. After user authorization, the client sends the original code_verifier with the token exchange request.
  5. The authorization server verifies that SHA256(code_verifier) == code_challenge before issuing the token.

This prevents authorization code interception attacks because an attacker who intercepts the code cannot exchange it without the original code_verifier.

Configuration

Property Description
OAuth2Options.GrantType Set to auth2CodePKCE.
OAuth2Options.ClientId The client identifier issued by the authorization server.
OAuth2Options.ClientSecret Optional. Some providers require it even with PKCE; others do not.
AuthorizationServerOptions.AuthURL The authorization endpoint URL where the user is redirected to authenticate.
AuthorizationServerOptions.TokenURL The token endpoint URL where the authorization code is exchanged for an access token.
AuthorizationServerOptions.Scope The scope of the access request.
LocalServerOptions.IP The IP address of the local redirect server (e.g., 127.0.0.1).
LocalServerOptions.Port The port of the local redirect server. Set to 0 for a random available port.

Example

OAuth2.OAuth2Options.GrantType := auth2CodePKCE;
OAuth2.OAuth2Options.ClientId := 'your-client-id';
OAuth2.AuthorizationServerOptions.AuthURL := 'https://provider.com/oauth2/authorize';
OAuth2.AuthorizationServerOptions.TokenURL := 'https://provider.com/oauth2/token';
OAuth2.AuthorizationServerOptions.Scope.Text := 'openid profile';
OAuth2.LocalServerOptions.IP := '127.0.0.1';
OAuth2.LocalServerOptions.Port := 0;
OAuth2.Start;

Random Port

When LocalServerOptions.Port is set to 0, the component automatically selects a random available port. This is recommended for desktop and mobile applications because it avoids port conflicts. The selected port is included in the redirect URI sent to the authorization server.

Token Refresh

PKCE flows typically return a refresh token. Use the Refresh method to obtain a new access token:

OAuth2.Refresh('your-refresh-token');

When to Use

Use the Authorization Code with PKCE grant for: