Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@plusauth/oidc-client-js

PlusAuth524MIT1.7.0TypeScript support: included

OpenID Connect (OIDC) and OAuth2 library for browser based JavaScript applications.

openid-connect, oidc, oidc client, oauth2, plusauth

readme

@plusauth/oidc-client-js

Build Status npm npm bundle size (scoped) npm bundle size (scoped) Codecov Vulnerabilities license

OpenID Connect (OIDC) and OAuth2 library for browser based JavaScript applications.

Features

  • Silent Authentication
  • Automatic Access Token Renewal
  • OAuth 2.0 Token Revocation
  • Session Management (with logout functionality)
  • PKCE
  • JWT payload validation
  • Can be used with any OAuth 2.0 / OpenID Connect provider
  • Cross tab/window login synchronization
  • Dispatches single request per tab/window to prevent inconsistency
  • Official TypeScript support

Table of Contents

Installation

From the CDN:

<script src="https://unpkg.com/@plusauth/oidc-client-js@1.5.0/dist/oidc-client.min.js"></script>

Using package managers:

npm install @plusauth/oidc-client-js
yarn add @plusauth/oidc-client-js
pnpm add @plusauth/oidc-client-js

Documentation

Initialization

Create the OIDCClient instance before rendering or initializing your application.

import { OIDCClient } from '@plusauth/oidc-client-js';

const oidcClient = new OIDCClient({
  issuer: 'YOUR_OIDC_PROVIDER',
  client_id: 'YOUR_CLIENT_ID',
  redirect_uri: 'YOUR_CALLBACK_PAGE_URI'
});

oidcClient.initialize().then( function(){
  // client initialized
})

Or with create helper method:

import createOIDCClient from '@plusauth/oidc-client-js';

createOIDCClient({
  issuer: 'YOUR_OIDC_PROVIDER',
  client_id: 'YOUR_CLIENT_ID',
  redirect_uri: 'YOUR_CALLBACK_PAGE_URI'
}).then(oidcClient => {
  //...
});

Using createOIDCClient does a couple of things automatically:

  • It creates an instance of OIDCClient.
  • It calls silentLogin to refresh the user session.
  • It suppresses all errors from silentLogin.

Create callback page

OpenID Connect / OAuth2 authorization flows require a redirect uri to return the authorization result back. Create a page and register its url to your client's allowed redirect uris. In your page initialize OIDCClient and all you need to do is call loginCallback method.

oidcClient.loginCallback()
.then( function(localState){
  // successful login
  console.log('User successfully logged in')
})
.catch( function(error) {
  console.error('Authorization error:', error)
 })

Login and get user info

Create a login button users can click.

<button id="login">Login</button>

In the click event handler of button you created, call login method for redirecting user to provider's login page . Make sure redirect_uri is registered on the provider, and you have created a callback handler as defined in above .

document.getElementById('login').addEventListener('click', function() {
  oidcClient.login({
    redirect_uri: 'http://localhost:8080/'
  });
});

Make authenticated requests to your API

After user is successfully logged in we can use access_token retrieved from authentication response to call the API.

<button id="makeRequest">Make Request</button>

On the event handler you can get access token and use it like this:

document.getElementById('makeRequest').addEventListener('click', function () {
 oidcClient.getAccessToken().then(accessToken =>
       fetch('https://any.exampleapi.com/api', {
         method: 'GET',
         headers: {
           Authorization: 'Bearer ' + accessToken
         }
       })
     )
     .then(result => result.json())
     .then(data => {
       console.log(data);
     });
});

Logout

Add a logout button.

<button id="logout">Logout</button>

In event handler, call equivalent method.

document.getElementById('logout').addEventListener('click', function(){
  oidcClient.logout();
});

Automatically renew access token

Generally, access tokens have a short lifetime, so it is common to renew the access token before its expiration. This feature is enabled by default, but you can disable it by passing autoSilentRenew: false to client options.

new OIDCClient({
  autoSilentRenew: false,
  ...// other options
})

Use different callback page for silent renew

In silent renew the library performs the flow in a hidden iframe. When you are developing a single page application, assuming your callback page is handled by the app itself, the iframe will load your whole application after the oauth2 redirection.

You can prevent this overhead by creating a different page which will handle silent renew only. To accomplish this you should pass silent_redirect_uri to client options which should have your silent redirect handler page uri. If you don't use silent_redirect_uri, redirect_uri will be used instead. Don't forget to include it to your providers redirect uri whitelist.

Have a look at following snippets for an example:

// auth.js
import { OIDCClient } from '@plusauth/oidc-client-js';

const oidcClient = new OIDCClient({
  redirect_uri: 'https://YOUR_SITE/callback'
  silent_redirect_uri: 'https://YOUR_SITE/silent-renew.html',
  ...//other options
});
<!-- silent-renew.html -->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <script src="https://unpkg.com/@plusauth/oidc-client-js/dist/plusauth-oidc-client.umd.js"></script>
</head>
<body>
<script type="application/javascript" >
    new PlusAuthOIDCClient.OIDCClient({
      issuer: 'YOUR_OIDC_PROVIDER'
    }).loginCallback()
</script>
</body>
</html>

Use Refresh Tokens for access token renewal

Configure the library by passing the setting useRefreshTokens to true on initialization:

const oidcClient = new OIDCClient({
  issuer: 'YOUR_OIDC_ISSUER',
  client_id: 'YOUR_CLIENT-ID',
  useRefreshTokens: true
});

Don't forget to include offline_access in your scope for retrieving refresh tokens. If there is not any refresh token stored locally, the library will fallback to using silent authorization request.

Login with popup

Create a button to trigger login.

<button id="loginWithPopup">Login</button>

Attach event listener and call loginWithPopup method of your initialized oidc client.

document.getElementById('loginWithPopup').click(async () => {
  await oidcClient.loginWithPopup();
});

Most browsers block popups if they are not happened as a result of user actions. In order to display login popup you must call `loginWithPopup` in an event handler listening for a user action like button click.

Additional methods

You can access user, access token, refresh token, id token and scopes with followings. Using getter methods are always the safe bet as they will read from store. Direct access of those variables may result unexpectedly if you modify them in your app. Direct variables are created by listening the user_login and user_logout events.

Get User

  const user = await oidcClient.getUser();
  // or
  const user = oidcClient.user

Get Access Token

  const accessToken = await oidcClient.getAccessToken();
  // or
  const accessToken = oidcClient.accessToken

Get ID Token

  const idToken = await oidcClient.getIdToken();
  // or
  const idToken = oidcClient.idToken

Get Refresh Token

  const refreshToken = await oidcClient.getRefreshToken();
  // or
  const refreshToken = oidcClient.refreshToken

Get Scopes

  const scopes = await oidcClient.getScopes();
  // or
  const scopes = oidcClient.scopes

Api Docs

Please visit here

Examples

Have a look at examples directory for various examples

Browser Support

Browserlist Coverage

This library uses global fetch api. If your app requires to be working in environment that does not have fetch you must use a polyfill like whatwg-fetch.

changelog

Changelog

1.6.0 (2025-04-03)

Bug Fixes

  • scopes method returns requested scopes if the AS returns empty scope (8a2deb1)

Features

  • filter empty strings from scopes (807d28d)

1.5.0 (2025-01-17)

Features

  • allow the library to be used in non-secure contexts (b384d5b)

1.4.2 (2024-08-21)

Bug Fixes

  • user state is not set on initialize when checkLogin = false (3bcb9a6)

1.4.1 (2023-10-17)

Bug Fixes

  • access token renewal wont start on inital load (c5f09f4)
  • synchronizer events not fired when localStorage is disabled (0cfae29)

1.4.0 (2023-09-08)

Features

  • options for providing custom state and nonce length (24970cc)

1.3.0 (2023-09-06)

Bug Fixes

  • incorrect getter for expires_in (d427e22), closes #17

Features

  • specific error when local state does not exist (b931a54)

1.2.5 (2023-05-12)

Bug Fixes

  • object merging behaves incorrectly for classes (6a6c09d), closes #14

1.2.4 (2023-05-06)

Bug Fixes

  • silent login options are not using client defaults. regression in v1.2.3 (d00e0f2)

1.2.3 (2023-05-04)

Bug Fixes

  • merge options properly, ignore undefined (cfd0cd8), closes #13

1.2.2 (2023-04-09)

1.2.1 (2023-03-27)

Bug Fixes

  • silent renew error not emitted on initialization (1ddc260)

1.2.0 (2023-03-14)

Bug Fixes

  • cannot override response mode and prompt for silent login (15c404e), closes #9
  • cannot override response mode for popup login (89359d2), closes #10
  • cannot resolve state if web message does not contain it (a9f899f)

Features

  • add getter for expires_at (9c8718e), closes #7

1.1.2 (2023-02-24)

Bug Fixes

  • response_mode param not included in auth request (d3767dc), closes #6

1.1.1 (2023-02-23)

Bug Fixes

  • get requests include headers resulting to fail with cors (2b5519a), closes #4

1.1.0 (2023-02-07)

Features

  • throw custom error when user closes popup (41ceb5d)

1.0.0 (2022-10-27)

Bug Fixes

  • retrying initialize attempts returns first failed response (918794e)

Features

  • silentRequestTimeout option (6001cdd)
  • accessor for raw idtoken (a999894)
  • allow objects in extra params (6b83144)
  • assume silent renew failed when no redirect happens (1aa6540)
  • claims parameter support (ee35343)
  • clear auth store when initialization fails (9e5c9b9)
  • do not fail initializing client when login checking fails (91c576e)

0.12.0 (2021-12-23)

Bug Fixes

  • accessibility warning for hidden iframe (417cb2f)

Features

  • try fetching oidc metadata from well-known endpoint in case of missing endpoints (0caec70)

0.11.0 (2021-12-20)

Bug Fixes

  • initialization promise is not waited correctly (4712244)
  • login synchronizing across tabs is not per issuer (906206e)
  • on login listener fails without localstorage (daa9a1e)
  • session is not checked on init (c504798)

Features

  • allow changing session checking interval (a626bb6)
  • check login only on initialization (4834080)
  • cross tab login synchronization (d7710e1)
  • throw error when auth endpoint is missing (b9fbb2f)
  • use tab utils instead of broadcast-channel (1397dca)

0.10.2 (2021-07-02)

Bug Fixes

  • incorrect issuer uri validation (aae260a), closes #2

Features

  • include search and hash params check in issuer validation (30dca0d)

0.10.1 (2021-06-28)

Bug Fixes

  • logout does not use id token raw (edd97e7)

0.10.0 (2021-06-17)

Bug Fixes

  • latest auth params are not passed to silent login with refresh_token (13edacf)
  • token issued time validations fails with decimal time (710e6db)

Features

  • separate methods for parsed and raw id token retrieval (6e6ca13)

0.9.0 (2021-05-26)

Bug Fixes

  • popup mode not resolving error (fa9c213)

Features

  • conform rfc4648 (jwt b64 url) (3d42976)

0.8.0 (2021-05-19)

Features

  • emit user logout on session change (0c9ba2c)

0.7.0 (2021-05-06)

Bug Fixes

  • errors in token requests are not thrown (310b41d)

Features

  • throw fetch errors on initialize (9c8c41a)

0.6.3 (2020-11-15)

0.6.2 (2020-11-15)

Bug Fixes

  • prevent multiple calls of initialize from sending oidc info request (e2c7bbf)

0.6.1 (2020-11-15)

Bug Fixes

  • silent login is called twice on initialize (e9035d0)

0.6.0 (2020-11-15)

Bug Fixes

  • silent login executed on session check error (4771d7d)

Features

  • add initialize check on silent login (b95d74a)

0.5.0 (2020-11-15)

Features

  • add corresponding events for silent renew and session checker (974cb53)

0.4.0 (2020-10-16)

0.3.0 (2020-10-08)

Features

  • return scope list from getScope (6647ac9)

0.2.0 (2020-10-08)

Bug Fixes

  • handle cases where expires_in is string (8b6c71e)

Features

  • add instance variables for direct access (62b7794)
  • check for userinfo endpoint before fetching userinfo (9479068)
  • in memory state store (5e40a00)
  • silent_redirect_uri support (3dc7a9f)
  • use in memory storage for auth store (9f3f820)

0.1.2-beta.0 (2020-10-06)

Bug Fixes

  • audience check fails for id_token (4e6874f)

0.1.1 (2020-10-06)

Bug Fixes

  • auth response params cannot be parsed if response type is fragment (5d5284d)
  • auth state get deleted whenever temporary state delete requested (b165cd3)
  • code challenge is generated always (c7d6bdb)
  • isLoggedIn returns wrong result (4e2343c)
  • logout event is not fired on session end (bdd75bf)
  • nonce is not generated when openid scope exists (6a01e86)
  • popup result is not passed to opener window (3c63b3a)

0.1.0 (2020-08-27)

Bug Fixes

  • cannot exchange authorization code in silent login (fe36a0f)
  • sso logout does not clear local auth store (80faf4a)

Features

  • add initialized flag (3115a0e)
  • add sub claim to user profile (4dfb78e)
  • use merged options in constructor (e1a8799)