@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-bundleUsage
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 flowrealm- Override the realm for this authenticationkc_idp_hint- Override the identity provider hint (e.g., "login.gov", "federation-eams")redirectUrl- Override the redirect URL after authenticationscope- Override the OAuth scopes (for direct-grant flow)
- String: Authentication 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– Returnstrueif 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– Returnstrueif 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 thedirectGrantUrlto parse the CAC certificate, andhttps://identity...as therefreshUrlto 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
redirectUrlis 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
persistActionsconfiguration.
