Low-Level OAuth 2 / OpenID Connect Client API

3.8.5 · active · verified Sun Apr 19

oauth4webapi is a low-level JavaScript client library for implementing OAuth 2.1, OAuth 2.0 (with Security BCPs), FAPI 2.0, and OpenID Connect protocols. It provides a comprehensive set of routines for authorization server metadata discovery, various grant flows (Authorization Code Flow with PKCE, Refresh Token, Device Authorization, CIBA, Client Credentials), DPoP, Token Introspection/Revocation, PAR, UserInfo requests, and JWT-secured mechanisms. The library emphasizes secure, up-to-date best practices and is designed to run consistently across browser and non-browser JavaScript runtimes, including Node.js, Deno, and Bun. Currently at version 3.8.5, it receives frequent patch and minor releases, indicated by the detailed changelog. A key differentiator is its zero-dependency footprint and OpenID Connect certification, promoting high-assurance security standards without external dependencies.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a basic OpenID Connect Authorization Code Flow with PKCE, covering discovery, authorization URL generation, and code exchange for tokens using Google as the IdP. It highlights key functions like `discover`, `generatePKCE`, `authorizationUrl`, and `exchangeCode`.

import { discover, calculatePKCEChallenge, generatePKCE, authorizationUrl, processAuthorizationResponse, exchangeCode, Issuer, Client, TokenEndpointResponse, JWKS } from 'oauth4webapi';

const as = await discover(new URL('https://accounts.google.com/.well-known/openid-configuration'));

const client: Client = {
  client_id: process.env.GOOGLE_CLIENT_ID ?? '',
  client_secret: process.env.GOOGLE_CLIENT_SECRET ?? '',
  token_endpoint_auth_method: 'client_secret_post'
};

const redirect_uri = 'http://localhost:3000/callback';

async function initiateOAuthFlow() {
  const pkce = generatePKCE();
  const code_challenge = await calculatePKCEChallenge(pkce);

  const authUrl = new URL(authorizationUrl(as, client, {
    redirect_uri,
    scope: 'openid email profile',
    response_type: 'code',
    code_challenge,
    code_challenge_method: 'S256',
    nonce: 'some-random-nonce'
  }));
  console.log('Please visit this URL to authenticate:', authUrl.toString());
  // In a real application, you would redirect the user to authUrl.
  // For this example, you'd manually visit and get the code from the callback.
}

async function handleCallback(requestUrl: string) {
  const currentUrl = new URL(requestUrl);
  const params = oauth.validateAuthResponse(as, client, currentUrl);

  if (oauth.is= (params instanceof Error)) {
    console.error('Authorization response error:', params);
    return;
  }

  const response = await exchangeCode(as, client, params.code, {
    redirect_uri,
    code_verifier: 'your_pkce_code_verifier_here' // Replace with actual verifier from initiateOAuthFlow
  });

  if (response instanceof Error) {
    console.error('Token exchange error:', response);
    return;
  }

  console.log('Access Token:', response.access_token);
  console.log('ID Token:', response.id_token);

  // Further validation and usage of tokens would follow
}

// Example usage (simplified for quickstart)
initiateOAuthFlow();
// To test handleCallback, you'd simulate a redirect after authentication
// handleCallback('http://localhost:3000/callback?code=YOUR_CODE_HERE&state=YOUR_STATE_HERE');

view raw JSON →