OpenID Connect (Authorization Code + PKCE)
The OIDC Authorization Code flow with PKCE end to end, using plain HTTP and curl, so you understand every step before reaching for a library.
This guide walks the Authorization Code flow with PKCE using nothing but HTTP, so you can see exactly what each step sends and receives. The Node and React guides do the same thing with a library; read this one first.
Make sure you have registered an application and a redirect URI as described in Before you start.
The flow in one picture
- Your app redirects the browser to the authorization endpoint with a PKCE challenge.
- The user signs in; the platform redirects back to your redirect URI with a one-time
code. - Your app exchanges the
code(plus the PKCE verifier) at the token endpoint for an ID token and access token. - Your app validates the ID token and, optionally, calls the UserInfo endpoint.
1. Create a PKCE verifier and challenge
Generate a random code verifier, then derive its SHA-256 code challenge:
# code verifier: 43-128 chars of unreserved characters
CODE_VERIFIER=$(openssl rand -base64 60 | tr -d '\n=+/' | cut -c1-64)
# code challenge: base64url(SHA256(verifier))
CODE_CHALLENGE=$(printf '%s' "$CODE_VERIFIER" | openssl dgst -binary -sha256 | openssl base64 | tr '+/' '-_' | tr -d '=\n')
echo "verifier: $CODE_VERIFIER"
echo "challenge: $CODE_CHALLENGE"import { createHash, randomBytes } from 'node:crypto';
const codeVerifier = randomBytes(48).toString('base64url'); // 64 chars
const codeChallenge = createHash('sha256').update(codeVerifier).digest('base64url');
console.log('verifier: ', codeVerifier);
console.log('challenge:', codeChallenge);import base64, hashlib, secrets
code_verifier = secrets.token_urlsafe(48) # 64 chars
digest = hashlib.sha256(code_verifier.encode("ascii")).digest()
code_challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()
print("verifier: ", code_verifier)
print("challenge:", code_challenge)import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
var random = new byte[48];
new SecureRandom().nextBytes(random);
var encoder = Base64.getUrlEncoder().withoutPadding();
var codeVerifier = encoder.encodeToString(random); // 64 chars
var codeChallenge = encoder.encodeToString(
MessageDigest.getInstance("SHA-256").digest(codeVerifier.getBytes(StandardCharsets.US_ASCII)));
System.out.println("verifier: " + codeVerifier);
System.out.println("challenge: " + codeChallenge);using System.Security.Cryptography;
using System.Text;
static string B64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
var codeVerifier = B64Url(RandomNumberGenerator.GetBytes(48)); // 64 chars
var codeChallenge = B64Url(SHA256.HashData(Encoding.ASCII.GetBytes(codeVerifier)));
Console.WriteLine($"verifier: {codeVerifier}");
Console.WriteLine($"challenge: {codeChallenge}");import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
)
random := make([]byte, 48)
rand.Read(random)
codeVerifier := base64.RawURLEncoding.EncodeToString(random) // 64 chars
sum := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(sum[:])
fmt.Println("verifier: ", codeVerifier)
fmt.Println("challenge:", codeChallenge)function b64url(string $bytes): string {
return rtrim(strtr(base64_encode($bytes), '+/', '-_'), '=');
}
$codeVerifier = b64url(random_bytes(48)); // 64 chars
$codeChallenge = b64url(hash('sha256', $codeVerifier, true));
echo "verifier: $codeVerifier\n";
echo "challenge: $codeChallenge\n";use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use rand::RngCore;
use sha2::{Digest, Sha256};
let mut random = [0u8; 48];
rand::thread_rng().fill_bytes(&mut random);
let code_verifier = URL_SAFE_NO_PAD.encode(random); // 64 chars
let code_challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(code_verifier.as_bytes()));
println!("verifier: {code_verifier}");
println!("challenge: {code_challenge}");Keep the verifier for step 3. Also generate a random state (and, if you check it, a nonce) to protect against cross-site request forgery and replay.
2. Send the user to the authorization endpoint
Open this URL in the browser (line-wrapped here for readability):
https://<your-domain>/authorize
?response_type=code
&client_id=<your-client-id>
&redirect_uri=https://app.example.com/callback
&scope=openid%20profile%20email%20offline_access
&state=<random-state>
&code_challenge=<CODE_CHALLENGE>
&code_challenge_method=S256scopemust includeopenid. Addprofileandemailfor the standard claims, andoffline_accessif you want a refresh token.- After the user signs in, the platform redirects to
https://app.example.com/callback?code=<one-time-code>&state=<random-state>. - Check that the returned
statematches the one you sent before continuing.
3. Exchange the code for tokens
Post the code and the PKCE verifier to the token endpoint.
For a confidential client, authenticate with the client secret (HTTP Basic shown here):
curl -X POST https://<your-domain>/oauth/token \
-u '<your-client-id>:<your-client-secret>' \
-d grant_type=authorization_code \
-d redirect_uri=https://app.example.com/callback \
-d code=<one-time-code> \
-d code_verifier=$CODE_VERIFIERFor a public client (no secret), send the client_id as a form field and rely on PKCE:
curl -X POST https://<your-domain>/oauth/token \
-d grant_type=authorization_code \
-d client_id=<your-client-id> \
-d redirect_uri=https://app.example.com/callback \
-d code=<one-time-code> \
-d code_verifier=$CODE_VERIFIERThe response contains the tokens:
{
"access_token": "<jwt>",
"id_token": "<jwt>",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "<token>",
"scope": "openid profile email offline_access"
}A refresh_token is present only if you requested offline_access and the application is allowed to receive one.
4. Validate the ID token
The ID token is a JWT that proves who signed in. Validate it before you trust it:
- Verify the signature against the platform's signing keys at
/.well-known/jwks. - Check
issmatches your instance,audmatches your client ID, and the token is not expired (exp). - If you sent a
nonce, check it matches.
The sub claim is the stable user identifier; profile and email scopes add claims such as name and email.
5. Call UserInfo (optional)
For claims beyond the ID token, call the UserInfo endpoint with the access token:
curl https://<your-domain>/userinfo \
-H 'Authorization: Bearer <access_token>'6. Log the user out (optional)
To end the session, send the user to the end-session endpoint:
https://<your-domain>/logout
?id_token_hint=<id_token>
&post_logout_redirect_uri=https://app.example.com/Register the post_logout_redirect_uri on your application first, the same way you register a redirect URI.
Troubleshooting
redirect_urimismatch. Theredirect_uriin steps 2 and 3 must be identical to each other and to a value registered on the application, compared character by character (scheme, host, port, path, trailing slash).invalid_grantat the token endpoint. The code is single-use and short-lived; request a fresh one. This also appears if thecode_verifierdoes not match thecode_challengeyou sent.invalid_client. The client authentication is wrong: a confidential client must send its secret; a public client must not, and must be registered as a public (PKCE) client.
Next
- Node / Express backend does this with a library.
- Python / Flask backend does the same in Python.
- React single-page app does it in the browser.