ExMCP.Authorization.PKCE (ex_mcp v0.9.0)

View Source

PKCE (Proof Key for Code Exchange) implementation for OAuth 2.1.

PKCE is required for all authorization code flows in OAuth 2.1 to prevent authorization code interception attacks.

Summary

Functions

Generates the code challenge from a code verifier using SHA256.

Generates a cryptographically secure code verifier.

Validates a code verifier against a code challenge.

Validates that a code verifier meets the RFC 7636 requirements.

Functions

generate_code_challenge(code_verifier)

@spec generate_code_challenge(String.t()) :: String.t()

Generates the code challenge from a code verifier using SHA256.

The code challenge is the base64url encoding of the SHA256 hash of the code verifier.

Example

challenge = PKCE.generate_code_challenge(verifier)
# => "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"

generate_code_verifier()

@spec generate_code_verifier() :: String.t()

Generates a cryptographically secure code verifier.

The code verifier is a high-entropy cryptographic random string using unreserved characters [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~" with a minimum length of 43 characters and maximum of 128 characters.

Example

verifier = PKCE.generate_code_verifier()
# => "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"

validate_challenge(code_verifier, code_challenge)

@spec validate_challenge(String.t(), String.t()) :: boolean()

Validates a code verifier against a code challenge.

This is typically used by the authorization server to verify the PKCE flow.

Example

PKCE.validate_challenge(verifier, challenge)
# => true

validate_verifier(code_verifier)

@spec validate_verifier(String.t()) :: :ok | {:error, String.t()}

Validates that a code verifier meets the RFC 7636 requirements.

Returns :ok if valid, or {:error, reason} if invalid.