subscribe

A new OAuth2 client for Javascript

Frustrated with the lack of well maintained, minimal OAuth2 libraries, I wrote my own. This new OAuth2 library is only 3KB gzipped, mainly because it has 0 dependencies and relies on modern APIs like fetch() and Web Crypto which are built in Node 18 (but it works with Polyfills on Node 14 and 16).

It has support for key features such as:

  • authorization_code with PKCE support.
  • password and client_credentials grants.
  • a fetch() wrapper that automatically adds Bearer tokens and refreshes them.
  • OAuth2 endpoint discovery via the Server metadata document (RFC8414).
  • OAuth2 Token Introspection (RFC7662).

If your server does support the meta-data document, here’s how simple the process can be:

client_credentials example

import { OAuth2Client } from '@badgateway/oauth2-client';

const client = new Client({
  clientId: '..',
  clientSecret: '..',
  server: 'https://my-auth-server.example'
});

const tokens = await client.clientCredentials();

Without the meta-data document, you will need to specify settings such as the tokenEndpoint and possibly the authorizationEndpoint depending on which flow you are using.

authorization_code example

The authorization_code flow is a multi-step process, so a bit more involved. The library gives you direct access to the primitives, allowing you to integrate in your own frameworks and applications.

import { OAuth2Client, generateCodeVerifier } from '@badgateway/oauth2-client';

const client = new OAuth2Client({
  server: 'https://authserver.example/',
  clientId: '...',
});

// Part of PCKE
const codeVerifier = await generateCodeVerifier();

// In a browser this might work as follows:
document.location = await client.authorizationCode.getAuthorizeUri({
  redirectUri: 'https://my-app.example/',
  state: 'some-string',
  codeVerifier,
  scope: ['scope1', 'scope2'],
});

Handling the redirect back

const oauth2Token = await client.authorizationCode.getTokenFromCodeRedirect(
  document.location,
  {
    redirectUri: 'https://my-app.example/',
    state: 'some-string',
    codeVerifier,
  }
);

Docs and download

Web mentions