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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@usace/create-keycloak-auth-bundle

v2.2.0

Published

A redux-bundler Bundle Creator to create a Keycloak Authentication bundle

Readme

Developer Documentation: createKeycloakAuthBundle

Overview

createKeycloakAuthBundle is a bundle factory for use with the redux-bundler state management library. It provides authentication and authorization functionalities using Keycloak, handling token management, role-based access control, session handling, and API authentication.

Installation

npm install @usace/create-keycloak-auth-bundle

Usage

import { createKeycloakAuthBundle } from "@usace/create-keycloak-auth-bundle";

const authBundle = createKeycloakAuthBundle({
  keycloakUrl: "https://keycloak.example.com",
  realm: "myrealm",
  client: "myclient",
  redirectUrl: "https://myapp.com",
  flow: "browser",
  refreshInterval: 300,
  sessionEndWarning: 600,
});

Configuration Options

The createKeycloakAuthBundle function accepts an options object with the following properties:

| Property | Type | Default | Description | | ------------------- | ------ | ------------------------- | ------------------------------------------------------------------------------------------------------------- | | name | string | "auth" | Unique name for the authentication bundle | | keycloakUrl | string | "http://localhost:8080" | Keycloak server root | | directGrantUrl | string | keycloakUrl | Keycloak URL to use for direct-grant, use the identityc variation here to get mutual-auth to work | | browserFlowUrl | string | keycloakUrl | Keycloak URL to use for browser flow | | refreshUrl | string | keycloakUrl | Keycloak URL to use for token refresh calls, use identity variation here to not prompt for CAC on refreshes | | realm | string | "default" | Keycloak realm name | | client | string | "default" | Keycloak client ID | | kc_idp_hint | string | "federation-eams" | Identity provider hint for Keycloak authentication (e.g., "federation-eams", "login.gov") | | flow | string | "direct-grant" | Authentication flow: direct-grant or browser | | redirectUrl | string | undefined | Redirect URL after authentication. If not provided, defaults to current page origin + pathname | | refreshInterval | number | 300 | Interval in seconds for refreshing tokens | | sessionEndWarning | number | 600 | Time in seconds before session end warning triggers | | mockToken | string | undefined | Provide a token for local testing, will set the token state without having to be tied to a keycloak instance |

Action Creators

The bundle automatically generates action creators for authentication operations:

doAuthLogin(flowOrOverrides)

Initiates the login process based on the configured flow.

Signatures:

// Legacy signature: Pass flow as string
store.doAuthLogin("browser");
store.doAuthLogin("direct-grant");

// New signature: Pass overrides object for runtime configuration
store.doAuthLogin({
  flowOverride: "browser",
  realm: "custom-realm",
  kc_idp_hint: "login.gov",
  redirectUrl: "https://myapp.com/callback",
  scope: "openid profile email"
});

Parameters:

  • flowOrOverrides (string | object):
    • String: Authentication flow ("browser" or "direct-grant")
    • Object: Override configuration with the following properties:
      • flowOverride - Override the authentication flow
      • realm - Override the realm for this authentication
      • kc_idp_hint - Override the identity provider hint (e.g., "login.gov", "federation-eams")
      • redirectUrl - Override the redirect URL after authentication
      • scope - Override the OAuth scopes (for direct-grant flow)

doAuthLogout()

Logs out the user and clears authentication state.

store.doAuthLogout();

doAuthUpdate(token, keycloakResponse)

Updates the authentication token in state.

store.doAuthUpdate(token, keycloakResponse);

Selectors

Generated selectors for accessing authentication state:

  • selectAuthToken – Returns the authentication token.
  • selectAuthTokenHeader – Returns the decoded token header.
  • selectAuthTokenPayload – Returns the decoded token payload.
  • selectAuthTokenExp – Returns the token expiration timestamp.
  • selectAuthTokenIsExpired – Returns true if the token is expired.
  • selectAuthKeycloakResponse – Returns the full Keycloak response object.
  • selectAuthRoles – Returns an array of user roles.
  • selectAuthRolesObj – Returns user roles as an object (e.g., { "admin": true, "user": true }).
  • selectAuthRolesCaseInsensitiveObj – Returns user roles as uppercase object keys.
  • selectAuthUsername – Returns the authenticated username.
  • selectAuthUserInitials – Returns the user initials.
  • selectAuthUserEmail – Returns the user email address from the token.
  • selectAuthIsLoggedIn – Returns true if the user is logged in.
  • selectAuthHasCodeFlowParams – Checks if URL contains code flow parameters.

API Helpers

Additional API helper functions for authenticated requests:

  • apiFetch(url, options) – Performs a fetch request with automatic token handling.
  • apiGet(url, callback) – Performs a GET request with authentication.
  • apiPost(url, payload, callback) – Performs a POST request with authentication.
  • apiPut(url, payload, callback) – Performs a PUT request with authentication.
  • apiDelete(url, payload, callback) – Performs a DELETE request with authentication.
  • anonGet(url, callback) – Performs a GET request without authentication.

Usage Examples

Basic Setup

import { createKeycloakAuthBundle } from "@usace/create-keycloak-auth-bundle";

const authBundle = createKeycloakAuthBundle({
  keycloakUrl: "https://identity.sec.usace.army.mil/auth",
  realm: "cwbi",
  client: "my-client-id",
  kc_idp_hint: "federation-eams",
  flow: "browser",
  refreshInterval: 300,
  sessionEndWarning: 600,
});

Standard Login Flow

// Using configured flow (browser or direct-grant)
store.doAuthLogin();

// Override flow at runtime
store.doAuthLogin("browser");

Dynamic Identity Provider Selection

// Let users choose their login method
function loginWithLoginGov() {
  store.doAuthLogin({
    flowOverride: "browser",
    kc_idp_hint: "login.gov"
  });
}

function loginWithEAMS() {
  store.doAuthLogin({
    flowOverride: "browser",
    kc_idp_hint: "federation-eams"
  });
}

Multi-Realm Authentication

// Authenticate to different realms dynamically
function loginToCustomRealm() {
  store.doAuthLogin({
    flowOverride: "browser",
    realm: "custom-realm",
    redirectUrl: "https://myapp.com/custom-callback"
  });
}

Direct Grant (X.509 / CAC) with Overrides

// Standard CAC authentication
store.doAuthLogin("direct-grant");

// CAC authentication with custom scope
store.doAuthLogin({
  flowOverride: "direct-grant",
  scope: "openid profile email custom-scope"
});

Accessing User Information

// Get user details from token
const username = store.selectAuthUsername();
const email = store.selectAuthUserEmail();
const initials = store.selectAuthUserInitials();
const roles = store.selectAuthRoles();

// Check specific roles
const rolesObj = store.selectAuthRolesObj();
if (rolesObj["admin"]) {
  // User has admin role
}

Making Authenticated API Calls

// Using apiFetch (recommended)
store.apiFetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => console.log(data));

// Using callback-based helpers
store.apiGet("https://api.example.com/data", (err, data) => {
  if (err) {
    console.error("API Error:", err);
  } else {
    console.log("Data:", data);
  }
});

store.apiPost("https://api.example.com/data", { key: "value" }, (err, data) => {
  // Handle response
});

Notes

  • CAC Authentication: When using CWBI Keycloak with CAC (X.509) authentication, use https://identityc... as the directGrantUrl to parse the CAC certificate, and https://identity... as the refreshUrl to avoid repeated CAC PIN prompts during token refresh.
  • Backward Compatibility: The doAuthLogin() method supports both legacy string parameters and new object-based overrides.
  • Dynamic Redirect: If redirectUrl is not configured, the bundle automatically uses the current page's origin and pathname.
  • Token Persistence: Tokens are automatically persisted and restored across page reloads using the persistActions configuration.