Sign in from a web app
The authorization code flow with PKCE for a server-rendered application, including state, nonce and token exchange.
A web application never collects a Versified password. It sends the browser to the provider, receives a short-lived code on the registered redirect URI, and exchanges that code — plus the PKCE verifier — for tokens on the server. This page describes Shape A; Choose your integration shape covers the alternatives and when each one wins.
1. Start the flow
import { createHash, randomBytes } from "node:crypto";
const base64url = (buffer: Buffer) =>
buffer
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
const verifier = base64url(randomBytes(32));
const challenge = base64url(createHash("sha256").update(verifier).digest());
const state = base64url(randomBytes(16));
const nonce = base64url(randomBytes(16));
// Persist verifier, state and nonce against this browser session.
const params = new URLSearchParams({
response_type: "code",
client_id: process.env.VERSIFIED_CLIENT_ID!,
redirect_uri: process.env.VERSIFIED_REDIRECT_URI!,
scope: "openid profile email offline_access",
code_challenge: challenge,
code_challenge_method: "S256",
state,
nonce,
});
// 302 to `${issuer}/auth?${params}`import base64, hashlib, os
from urllib.parse import urlencode
def b64url(raw: bytes) -> str:
return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()
verifier = b64url(os.urandom(32))
challenge = b64url(hashlib.sha256(verifier.encode()).digest())
state = b64url(os.urandom(16))
nonce = b64url(os.urandom(16))
# Persist verifier, state and nonce against this browser session.
params = {
"response_type": "code",
"client_id": os.environ["VERSIFIED_CLIENT_ID"],
"redirect_uri": os.environ["VERSIFIED_REDIRECT_URI"],
"scope": "openid profile email offline_access",
"code_challenge": challenge,
"code_challenge_method": "S256",
"state": state,
"nonce": nonce,
}
# 302 to f"{issuer}/auth?{urlencode(params)}"import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
// Inside your sign-in controller.
static String b64url(byte[] raw) {
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw);
}
static byte[] randomBytes(int size) {
var bytes = new byte[size];
new SecureRandom().nextBytes(bytes);
return bytes;
}
static String authorizeUrl(String issuer) throws Exception {
String verifier = b64url(randomBytes(32));
String challenge = b64url(MessageDigest.getInstance("SHA-256")
.digest(verifier.getBytes(StandardCharsets.US_ASCII)));
Map<String, String> params = new LinkedHashMap<>();
params.put("response_type", "code");
params.put("client_id", System.getenv("VERSIFIED_CLIENT_ID"));
params.put("redirect_uri", System.getenv("VERSIFIED_REDIRECT_URI"));
params.put("scope", "openid profile email offline_access");
params.put("code_challenge", challenge);
params.put("code_challenge_method", "S256");
params.put("state", b64url(randomBytes(16)));
params.put("nonce", b64url(randomBytes(16)));
// Persist verifier against this browser session, then redirect.
return issuer + "/auth?" + params.entrySet().stream()
.map(e -> e.getKey() + "=" +
URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
}PKCE is mandatory
An authorization request without code_challenge and code_challenge_method=S256 is rejected for every profile, including confidential web clients.
2. Handle the callback
// Reject a state that does not match the value you stored.
// Reject an error parameter before anything else.
const { code, state } = new URL(request.url).searchParams;
const response = await fetch(`${issuer}/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "authorization_code",
code: code!,
redirect_uri: process.env.VERSIFIED_REDIRECT_URI!,
client_id: process.env.VERSIFIED_CLIENT_ID!,
// Only sent by a confidential client.
client_secret: process.env.VERSIFIED_CLIENT_SECRET!,
code_verifier: verifier,
}),
});
const tokens = await response.json();
// { access_token, id_token, refresh_token, token_type, expires_in, scope }import os
import requests
# Reject a state that does not match the value you stored.
response = requests.post(
f"{issuer}/token",
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": os.environ["VERSIFIED_REDIRECT_URI"],
"client_id": os.environ["VERSIFIED_CLIENT_ID"],
# client_secret: confidential profiles only
"client_secret": os.environ["VERSIFIED_CLIENT_SECRET"],
"code_verifier": verifier,
},
timeout=10,
)
response.raise_for_status()
tokens = response.json()
# { access_token, id_token, refresh_token, token_type, expires_in, scope }import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
// Reject a state that does not match the value you stored.
Map<String, String> form = new LinkedHashMap<>();
form.put("grant_type", "authorization_code");
form.put("code", code);
form.put("redirect_uri", System.getenv("VERSIFIED_REDIRECT_URI"));
form.put("client_id", System.getenv("VERSIFIED_CLIENT_ID"));
form.put("client_secret", System.getenv("VERSIFIED_CLIENT_SECRET"));
form.put("code_verifier", verifier); // confidential only
String body = form.entrySet().stream()
.map(e -> e.getKey() + "=" +
URLEncoder.encode(e.getValue(), StandardCharsets.UTF_8))
.collect(Collectors.joining("&"));
HttpRequest request = HttpRequest.newBuilder(URI.create(issuer + "/token"))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(body))
.build();
String json = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofString()).body();
// json: { access_token, id_token, refresh_token, expires_in, scope }3. Turn the identity into a session
Verify the ID token — signature against the JWKS, iss, aud, exp and the nonce you just sent — and use its sub as the person. Do not use the email address as a key: people change email addresses, and sub is stable forever.
- Store the access token, refresh token and expiry in a server-side session store.
- Never hand the access token to the browser. Your BFF calls your API, not the page.
- Serialize refreshes. Two concurrent refreshes race the rotation and one of them loses, which looks exactly like a compromise.
4. Refresh
const response = await fetch(`${issuer}/token`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: session.refreshToken,
client_id: process.env.VERSIFIED_CLIENT_ID!,
client_secret: process.env.VERSIFIED_CLIENT_SECRET!,
}),
});
// The response carries a NEW refresh token. Replace the stored one atomically.
// Presenting a rotated-away refresh token is treated as compromise.Rotation is single-use
Refresh tokens live 30 days and rotate on every use. If your session store cannot replace the token atomically, a retried request will invalidate the session.
Reference implementation
Both first-party frontends run this flow behind a backend-for-frontend: the Next.js route handlers in src/app/api/auth hold the PKCE state, the callback, the encrypted Redis session and the reverse proxy that injects the bearer token. Read Sessions, logout and revocation for the lifecycle rules that go with it.
Something here out of date or unclear?
The platform team answers integration questions directly.
