npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@usace/keycloak

v2.0.1

Published

A minimalist, zero-dependency, Keycloak JavaScript class to support a limited subset of authentication workflows

Downloads

396

Readme

USACE Keycloak JS v2

Minimal, modern Keycloak authentication and token management for browser apps.

NPM Package: @usace/keycloak
Version: 2.0.1

Installation

npm install @usace/keycloak

Or with yarn:

yarn add @usace/keycloak

Import

import Keycloak, { tokenToObject } from "@usace/keycloak";

Quick Start

import Keycloak from "@usace/keycloak";

const kc = new Keycloak({
  client: "my-client",
  keycloakUrl: "https://identity.sec.usace.army.mil/auth",
  realm: "cwbi",
  redirectUrl: window.location.origin + "/callback",
  onAuthenticate: (token, keycloakResponse) => {
    // User is authenticated, do something with token!
    console.log("Access Token:", token);
  },
  onSessionEnding: (secondsLeft) => {
    alert(`Your session will expire in ${secondsLeft} seconds.`);
  },
  onError: (err) => {
    alert("Keycloak error: " + err);
  },
});

// To start login:
kc.authenticate();

// On callback route, handle token exchange:
kc.checkForSession();

Configuration Options

Pass these as an object to the Keycloak constructor:

| Option | Type | Default | Description | | ------------------- | -------- | ---------------- | ------------------------------------------------------------------------------------ | | client | string | — | Keycloak client ID (required) | | keycloakUrl | string | — | Base URL to Keycloak instance (required) | | realm | string | — | Realm name (required) | | redirectUrl | string | — | URL to redirect after login (required) | | logoutUrl | string | — | Base Keycloak URL for logout (defaults to keycloakUrl if not set) | | directGrantUrl | string | keycloakUrl | URL for direct grant/token endpoint | | browserFlowUrl | string | keycloakUrl | URL for browser login flow | | refreshUrl | string | keycloakUrl | URL for refresh endpoint | | kc_idp_hint | string | "login.gov" | Identity provider hint | | scope | string | "openid profile" | OAuth scopes | | refreshInterval | number | (from token) | Override refresh interval (seconds) | | refreshBuffer | number | 60 | Buffer (seconds) before token expiry to refresh | | sessionEndWarning | number | 60 | Warn user (seconds) before session expiry | | accessToken | string | — | Initial access token, if known | | identityToken | string | — | Initial identity token, if known | | refreshToken | string | — | Initial refresh token, if known | | Callbacks: | | | | | onAuthenticate | function | — | Called after authentication/refresh with access token and the full keycloak response | | onSessionEnding | function | — | Called before session expiry (seconds left) | | onError | function | throws Error | Called on authentication error | | onLogout | function | — | Called after programmatic logout (non-redirect) |


API Reference

Constructor

const kc = new Keycloak(options);

authenticate()

Redirects the browser to the Keycloak login page to initiate the browser authentication flow.

kc.authenticate();

checkForSession()

Checks the current URL for an authorization code, exchanges it for tokens, and triggers onAuthenticate.

kc.checkForSession();

Call this on your redirect/callback page after login!


refresh()

Refreshes the access token using the refresh token, if available.

kc.refresh();

directGrantAuthenticate(user, pass)

Logs in using the OAuth2 "Resource Owner Password" grant. Not recommended for browser use unless strictly required.

kc.directGrantAuthenticate("username", "password");

directGrantX509Authenticate()

Attempts to authenticate using X.509 client certificate to implement AJAX based CAC auth.

Note when using CWBI Keycloak, https://identity... does not parse the CAC certificate, https://identityc... will parse the CAC certificate. For the best user experience, use the c endpoint as the directGrantUrl and the non-c endpoint as the keycloakUrl so the user is not prompted for CAC pin when refreshing tokens.


getAccessToken() / getIdentityToken()

Get the most recently stored tokens:

const accessToken = kc.getAccessToken();
const idToken = kc.getIdentityToken();

logout({ redirect = true } = {})

Log out of Keycloak.

  • redirect (default true): redirect the browser to Keycloak’s logout endpoint (recommended for browser SSO).
  • If redirect is false, uses a back-channel (POST) logout.
// Redirect to logout page (user logged out everywhere):
kc.logout(); // or kc.logout({redirect: true})

// Programmatic logout (no redirect, just token revocation):
kc.logout({ redirect: false });

Token Parsing Utility

import { tokenToObject } from "@usace/keycloak";

// Decode JWT access or ID token to a JS object:
const payload = tokenToObject(accessToken);
console.log(payload.sub); // user id

Callback Hooks

Provide these as options to the constructor for more control:

  • onAuthenticate(token | { accessToken, identityToken, refreshToken }) Called after successful authentication or token refresh.

  • onSessionEnding(secondsLeft) Warn the user when their session is about to expire.

  • onError(error) Handles any error from authentication or token refresh.

  • onLogout() Called after a non-redirecting logout completes.


Usage Examples

1. Standard Login Flow

const kc = new Keycloak({...});
kc.authenticate();
// ... user logs in, Keycloak redirects to your redirectUrl ...
kc.checkForSession();

2. Refresh Token on Demand

setInterval(() => {
  kc.refresh();
}, 10 * 60 * 1000); // every 10 minutes (optional, as refresh is handled automatically)

3. Decode Token Claims

const info = tokenToObject(kc.getAccessToken());
console.log(info.email, info.preferred_username);

Best Practices & Notes

  • Always call kc.checkForSession() on your redirect URI after login when using browser flow.
  • The library automatically schedules token refreshes before expiry.
  • Configure valid redirect URIs for your Keycloak client.
  • Never expose client secrets in client-side code.
  • Do not use the username/password direct grant flow unless necessary.
  • Handle errors in the onError callback.

Release Notes

Version 2.0.0

  • Complete refactor for clarity and modern browser flows
  • Cleaner API and callback pattern
  • Improved error handling
  • Should be backwards compatible with 1.x releases, but not guaranteed.

License

MIT (or your organization’s standard license)



Let me know if you want to tweak any section or add badges, CI, or advanced troubleshooting!