How to generate code_verifier and code_challenge for OIDC Authorization


You can generate code_verifier and code_challenge for OIDC authorization as follows. The following codes are also on Gist.

JavaScript

F#

Python

Ruby

Shell Script


PKCE, Proof Key for Code Exchange

Coder verifier and code challenge are elements that are used in PKCE mechanizm. PKCE is a security enhancement for OAuth 2.0 and OpenID Connect (OIDC) authorization flows. It is primarily used to protect against authorization code interception attacks.

Here’s how it works.

Authorization Code Flow

  • In the standard OAuth 2.0 authorization code flow, a client application requests an authorization code from the authorization server.
  • The authorization code is then exchanged for an access token.
  • However, this flow is vulnerable to interception attacks, especially in mobile or single-page applications.

PKCE to the Rescue

  • PKCE introduces an additional step before exchanging the authorization code for an access token.
  • The client generates a random code verifier and computes its hashed value (the code challenge).
  • The code verifier is sent to the authorization server during the initial authorization request.
  • The server stores the code challenge associated with the authorization code.
  • When the client exchanges the authorization code for an access token, it must also send the original code verifier.
  • The server verifies that the code verifier matches the stored code challenge.

Why Is PKCE Important?

  • PKCE prevents attackers from intercepting the authorization code and using it to obtain an access token.
  • Even if an attacker captures the authorization code, they won’t have the corresponding code verifier.
  • This makes it much harder to perform token theft.

Usage

  • PKCE is recommended for all public clients (e.g., mobile apps, single-page apps) that use the authorization code flow.
  • Confidential clients (e.g., server-side applications) can also use PKCE for added security.

Remember, PKCE is like a secret handshake between your app and the authorization server, ensuring that only the intended recipient can complete the authorization process.