Skip to content

Instantly share code, notes, and snippets.

@krestenlaust
Created March 1, 2026 11:11
Show Gist options
  • Select an option

  • Save krestenlaust/935d77033c92ba0e56d6f039848b4e5e to your computer and use it in GitHub Desktop.

Select an option

Save krestenlaust/935d77033c92ba0e56d6f039848b4e5e to your computer and use it in GitHub Desktop.
OIDC Public authorization code - PKCE callback handler
const clientId = "demo";
const tokenAuthEndpoint = "http://127.0.0.1:8000/o/token/"
async function handleCallback() {
const params = new URLSearchParams(window.location.search);
const code = params.get("code");
const returnedState = params.get("state");
if (!code || !returnedState){
console.log("No code or state");
return;
}
const expectedState = sessionStorage.getItem("oidc_state");
const verifier = sessionStorage.getItem("pkce_verifier");
if (returnedState !== expectedState) {
throw new Error("Invalid authentication response";
}
sessionStorage.removeItem("oidc_state");
// Exchange code for tokens
const response = await fetch(tokenAuthEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: new URLSearchParams({
client_id: clientId,
code_verifier: verifier,
grant_type: "authorization_code",
redirect_uri: location.origin + location.pathname,
code
})
});
if (!response.ok) {
throw new Error(`Token request failed: ${response.status}`);
}
// Bearer token, scopes etc.
const tokenResponse = await response.json();
console.log(tokenResponse);
}
handleCallback();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment