@sgpinkus/keycloak-js
TypeScript icon, indicating that this package has built-in type declarations

1.0.8 • Public • Published

KEYCLOCK-JS-SIMPLE

A simpler, less stateful, API compatibl-ish replacement for the official keycloak-js adapter. Only supports code authentication flow (since implicit is deprecated).

INSTALLATION

npm i @sgpinkus/keycloak-js

USAGE

import { Keycloak } from '@sgpinkus/keycloak-js';
const kc = new Keycloak({
  authServerUrl: 'http://localhost:8080',
  realm: 'testing',
  clientId: 'testing',
};

// Is this a OAuth callback?
const response = await kc.processCodeFlowCallbackUrl(window.location.href);
if(!response) {
  console.debug('Not an OAuth response');
  // Forcing a login.
  window.location.href = kc.getLoginUrl();
} else {
  setMyTokens(response);
}

// Do your own work to verify and manage token. Resource servers receiving token must validate ...
function setMyTokens(tokens) {
  const { iatLocal } = tokens;
  const { exp, iat } = tokens.accessTokenParsed;
  const skew = iat - iatLocal;
  const now = Math.floor(new Date().getTime()/1000);
  const refreshAt = exp - iat - skew;
  if(refreshAt <= 0) {
    console.error(`Token expired [now=${now}, exp=${exp}, iat=${iat}]`);
    clearMyTokens();
    return;
  }
  if(skew) {
    console.warn(`Auth server is ${skew} seconds in front of local`);
  }
  stashMyTokens(tokens); // Use later in call to remote resource servers.
  console.log(`Setting refresh for ${refreshAt} seconds from now`)
  clearTimeout(refreshTimerId);
  refreshTimerId = setTimeout(() => refreshMyTokens(), refreshAt*1000);
}

See sample-app for complete example.

Readme

Keywords

Package Sidebar

Install

npm i @sgpinkus/keycloak-js

Weekly Downloads

7

Version

1.0.8

License

MIT

Unpacked Size

443 kB

Total Files

9

Last publish

Collaborators

  • sgpinkus