Unidy Docs

Authorization Code with PKCE

Implement secure browser or mobile authorization.

Sign a user in from a browser or native application with Authorization Code and an S256 PKCE challenge. PKCE binds the token exchange to the application instance that started the request. Public clients send no client secret; confidential clients use PKCE and client authentication.

Before you begin

Ask an administrator to create an OAuth application with:

  • Confidential cleared for a browser or native client.
  • Your exact callback URI, for example https://app.example.com/auth/callback.
  • The scopes you need: start with openid profile email for sign-in.
  • A separate Post-logout redirect URI if you will return to your application after signing out.

Obtain the application's UID as client_id and the trusted tenant issuer. Configure these explicitly; do not derive the issuer from an untrusted callback parameter. A public client does not send a secret, even if the dashboard has a secret field for the application. Use discovery for endpoints and signing keys.

Production redirects use HTTPS by default. Development, staging, and deployments configured to permit insecure redirects may differ; register HTTPS destinations for production. Prefer literal callback URIs over wildcard patterns. Changes in path, port, trailing slash, or query parameters can prevent a match.

The flow

Send the browser to the authorization endpoint for interactive login. A native app should use the platform's system authentication browser and secure transaction storage. Token exchange is an HTTP request; the interactive authorization step is a navigation.

Browser starter

This example uses openid-client 6.8.8 with a browser bundler and Web Crypto. Replace the issuer, client ID, and callback URI. Unidy currently allows cross-origin requests to discovery, token, and signing-key endpoints; a deployment proxy must also permit those requests. Keep the callback page free of third-party scripts and unrelated requests.

bash
npm install openid-client@6.8.8

Put the following in auth.ts. It keeps one pending login per browser tab and removes the transaction on success or failure. Starting another login in the same tab replaces the pending one.

typescript
import * as oidc from 'openid-client';

const issuer = new URL('https://login.example.com');
const clientId = 'YOUR_APPLICATION_UID';
const redirectUri = 'https://app.example.com/auth/callback';
const transactionKey = 'unidy.oidc.transaction';

let configuration: Promise<oidc.Configuration> | undefined;
function configure() {
  return configuration ??= oidc.discovery(
    issuer, clientId, { id_token_signed_response_alg: 'RS256' }, oidc.None(),
  )
    .then(config => {
      oidc.enableNonRepudiationChecks(config);
      return config;
    })
    .catch(error => {
      configuration = undefined;
      throw error;
    });
}

export async function beginLogin() {
  const config = await configure();
  const verifier = oidc.randomPKCECodeVerifier();
  const state = oidc.randomState();
  const nonce = oidc.randomNonce();
  const challenge = await oidc.calculatePKCECodeChallenge(verifier);
  sessionStorage.setItem(transactionKey, JSON.stringify({
    verifier, state, nonce, createdAt: Date.now(),
  }));
  const url = oidc.buildAuthorizationUrl(config, {
    response_type: 'code', redirect_uri: redirectUri,
    scope: 'openid profile email', state, nonce,
    code_challenge: challenge, code_challenge_method: 'S256',
  });
  window.location.assign(url.href);
}

export async function completeLogin() {
  const callback = new URL(window.location.href);
  const registered = new URL(redirectUri);
  const stored = sessionStorage.getItem(transactionKey);
  // Consume this transaction even if validation or the exchange fails.
  sessionStorage.removeItem(transactionKey);
  try {
    if (callback.origin !== registered.origin || callback.pathname !== registered.pathname) {
      throw new Error('Unexpected callback URL');
    }
    if (!stored) throw new Error('Start a new sign-in');
    const transaction = JSON.parse(stored);
    if (![transaction.verifier, transaction.state, transaction.nonce]
      .every(value => typeof value === 'string' && value.length > 0)
      || !Number.isFinite(transaction.createdAt)
      || Date.now() < transaction.createdAt
      || Date.now() - transaction.createdAt > 10 * 60 * 1000) {
      throw new Error('Missing or expired sign-in transaction');
    }
    const states = callback.searchParams.getAll('state');
    if (states.length !== 1 || !states[0] || states[0] !== transaction.state) {
      throw new Error('Sign-in state mismatch');
    }
    const tokens = await oidc.authorizationCodeGrant(await configure(), callback, {
      pkceCodeVerifier: transaction.verifier,
      expectedState: transaction.state,
      expectedNonce: transaction.nonce,
      idTokenExpected: true,
    });
    const claims = tokens.claims();
    if (!claims) throw new Error('Missing validated ID token');
    const now = Math.floor(Date.now() / 1000);
    if (typeof claims.iat !== 'number' || claims.iat > now + 60 || claims.iat < now - 300) {
      throw new Error('ID token issue time is outside the accepted window');
    }
    return { tokens, claims };
  } finally {
    // Keep authorization codes and error details out of history/referrer URLs.
    window.history.replaceState(null, '', registered.pathname);
  }
}

Call beginLogin() from your sign-in button. On /auth/callback, call completeLogin() once; only create signed-in application state from its successful result. Use (claims.iss, claims.sub) as the account key. Catch failures, show a safe sign-in error, and let the user start a new transaction. The library handles OAuth error callbacks, token-endpoint failures, required OIDC claims, issuer, audience, expiry, nonce, and—with the configured non-repudiation checks—the JWT signature. Do not replace those checks with JWT decoding.

The helper returns tokens to your application's session layer; it does not persist them automatically. Keep them out of URLs, analytics, logs, and unprotected persistent storage. A browser application's scripts can access its tokens, so use a server session instead if your architecture requires server-only credentials. See ID tokens and claims for the claim contract, and refresh and logout before adding session persistence.

The example has been type-checked and exercised against a mocked provider. Complete a real sign-in and failure-path check against your configured tenant before release.

Request reference

Authorization parameterValue
client_idYour application's UID.
response_typecode.
redirect_uriThe registered callback, identical to the URI used during exchange.
scopeSpace-separated requested scopes; include openid for an ID token.
stateA fresh random transaction value; require a non-empty exact match on callback.
nonceA fresh random value stored with the transaction and checked in the initial ID token.
code_challengeURL-safe, unpadded base64 of SHA-256 of the verifier.
code_challenge_methodS256.

A verifier contains 43–128 characters: A–Z, a–z, 0–9, -, ., _, and ~. Generate a new one with cryptographically secure randomness for each request and retain it only until callback processing finishes. The challenge is the SHA-256 digest encoded as URL-safe base64 with trailing = padding removed; a hexadecimal SHA-256 string is not an S256 challenge. Unidy supports PKCE but does not currently force every client to supply a challenge. Always enable S256 in your client configuration; do not rely on the server to reject an unprotected request.

The token exchange is a form-encoded POST to the discovered token endpoint with grant_type=authorization_code, client_id, code, redirect_uri, and code_verifier. A public client sends no secret. Once a challenge is attached to a code, the matching verifier is required even if a confidential client also authenticates.

The code is single use and normally expires after ten minutes. Exchange it promptly; starting a new authorization request is the recovery for a failed or expired transaction.

Handle the token response

A successful code exchange returns an access token, its expires_in, a refresh token, and an ID token when openid was granted. Use the access token for API requests, the validated ID token to establish identity, and the refresh token to obtain replacement tokens. Userinfo returns the current claims allowed by the granted scopes; verify that its sub matches the signed-in subject before combining it with the profile.

An access token issued for a user works only on REST operations that accept user-authorized access and the granted scopes. It does not grant every administrative API operation. Check the user-authorized access contract before choosing an endpoint.

Read expires_in instead of hardcoding the default two-hour access-token lifetime. Refresh rotates tokens with deferred parent revocation, and scheduled cleanup also limits how long old token rows remain usable. Keep the raw ID token securely if you will use it as a logout hint. The complete rules belong to token refresh, sessions, and logout.

Troubleshooting

ResultCheck or recovery
State mismatch, missing transaction, or stale callbackDo not exchange the code. Remove the transaction and start sign-in again.
access_deniedThe user declined authorization; return to your signed-out UI.
invalid_clientCheck the client ID and whether a browser client was incorrectly marked Confidential.
invalid_grant during exchangeCheck code reuse/expiry, callback URI, and the verifier associated with this request.
invalid_request involving code_verifierThe authorization request included a challenge; send its original verifier.
Redirect rejectedCompare the registered URI with the exact URI sent and check deployment HTTPS rules.
invalid_scope or a missing expected scopeCompare requested and application-configured scopes. Known custom scopes not assigned to the app can be omitted instead of failing the request; inspect the granted scope.
Browser network/CORS errorCheck the actual endpoint response and any proxy-level CORS restrictions. Do not solve it by shipping a confidential secret to the browser.

For session checks without interactive UI, use silent authentication with its browser-cookie limitations. Do not use it as a replacement for token refresh.

Was this page helpful?