CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-keycloak--keycloak-admin-client

A comprehensive TypeScript client library for interacting with Keycloak's Administration API.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

client-configuration.mddocs/

Client Configuration and Authentication

The KeycloakAdminClient class serves as the main entry point for all administrative operations. It handles authentication, token management, and provides access to all resource endpoints.

Capabilities

KeycloakAdminClient Class

The main client class that initializes all resource endpoints and manages connection configuration.

/**
 * Main Keycloak Admin Client class providing access to all administrative functionality
 */
class KeycloakAdminClient {
  // Resource instances - all Keycloak API endpoints
  public users: Users;
  public userStorageProvider: UserStorageProvider;
  public groups: Groups;
  public roles: Roles;
  public organizations: Organizations;
  public clients: Clients;
  public realms: Realms;
  public clientScopes: ClientScopes;
  public clientPolicies: ClientPolicies;
  public identityProviders: IdentityProviders;
  public components: Components;
  public serverInfo: ServerInfo;
  public whoAmI: WhoAmI;
  public attackDetection: AttackDetection;
  public authenticationManagement: AuthenticationManagement;
  public cache: Cache;

  // Connection settings
  public baseUrl: string;
  public realmName: string;
  public scope?: string;
  public accessToken?: string;
  public refreshToken?: string;

  /**
   * Initialize Keycloak Admin Client
   * @param connectionConfig - Optional configuration for connection settings
   */
  constructor(connectionConfig?: ConnectionConfig);

  // Authentication methods
  auth(credentials: Credentials): Promise<void>;
  registerTokenProvider(provider: TokenProvider): void;
  setAccessToken(token: string): void;
  getAccessToken(): Promise<string | undefined>;

  // Configuration methods
  setConfig(connectionConfig: ConnectionConfig): void;
  getRequestOptions(): RequestInit | undefined;
  getGlobalRequestArgOptions(): Pick<RequestArgs, "catchNotFound"> | undefined;
}

Usage Examples:

import KeycloakAdminClient from "@keycloak/keycloak-admin-client";

// Basic initialization
const kcAdminClient = new KeycloakAdminClient();

// With custom configuration
const kcAdminClient = new KeycloakAdminClient({
  baseUrl: "https://keycloak.example.com",
  realmName: "my-realm",
  requestOptions: {
    headers: {
      "Custom-Header": "value",
    },
    timeout: 10000,
  },
  requestArgOptions: {
    catchNotFound: true, // Return undefined instead of throwing on 404
  },
});

// Access resources
const users = await kcAdminClient.users.find();
const realms = await kcAdminClient.realms.find();

Connection Configuration

Configuration interface for customizing client connection behavior.

/**
 * Configuration options for Keycloak Admin Client connection
 */
interface ConnectionConfig {
  /** Base URL of Keycloak server (default: "http://127.0.0.1:8180") */
  baseUrl?: string;
  /** Realm name for authentication and operations (default: "master") */
  realmName?: string;
  /** Custom request options passed to all HTTP calls */
  requestOptions?: RequestInit;
  /** Global options for request arguments */
  requestArgOptions?: Pick<RequestArgs, "catchNotFound">;
}

/**
 * Request argument options for customizing API behavior
 */
interface RequestArgs {
  /** Return undefined instead of throwing NetworkError on 404 responses */
  catchNotFound?: boolean;
}

Authentication

Multiple authentication methods for different use cases and deployment scenarios.

/**
 * Authenticate using credentials and obtain access token
 * @param credentials - Authentication credentials with grant type
 */
auth(credentials: Credentials): Promise<void>;

/**
 * Supported OAuth2 grant types for authentication
 */
type GrantTypes = "client_credentials" | "password" | "refresh_token";

/**
 * Authentication credentials for different grant types
 */
interface Credentials {
  /** Username for password grant type */
  username?: string;
  /** Password for password grant type */
  password?: string;
  /** OAuth2 grant type */
  grantType: GrantTypes;
  /** Client ID for authentication */
  clientId: string;
  /** Client secret for confidential clients */
  clientSecret?: string;
  /** TOTP code for two-factor authentication */
  totp?: string;
  /** Request offline token for refresh capability */
  offlineToken?: boolean;
  /** Refresh token for refresh_token grant type */
  refreshToken?: string;
  /** OAuth2 scopes to request */
  scopes?: string[];
}

Authentication Examples:

// Username/password authentication (admin-cli client)
await kcAdminClient.auth({
  username: "admin",
  password: "admin",
  grantType: "password",
  clientId: "admin-cli",
});

// Client credentials authentication (service account)
await kcAdminClient.auth({
  grantType: "client_credentials",
  clientId: "my-service-client",
  clientSecret: "client-secret-here",
});

// Refresh token authentication
await kcAdminClient.auth({
  grantType: "refresh_token",
  clientId: "admin-cli",
  refreshToken: "refresh-token-here",
});

// Authentication with custom scopes
await kcAdminClient.auth({
  username: "admin",
  password: "admin",
  grantType: "password",
  clientId: "admin-cli",
  scopes: ["openid", "profile", "email"],
});

Token Management

Advanced token handling for custom authentication flows and external token sources.

/**
 * Custom token provider interface for external authentication
 */
interface TokenProvider {
  /** Function to retrieve access token from external source */
  getAccessToken: () => Promise<string | undefined>;
}

/**
 * Register custom token provider for external authentication
 * @param provider - Token provider implementation
 */
registerTokenProvider(provider: TokenProvider): void;

/**
 * Manually set access token (bypasses authentication)
 * @param token - JWT access token
 */
setAccessToken(token: string): void;

/**
 * Get current access token (from auth or token provider)
 * @returns Current access token or undefined
 */
getAccessToken(): Promise<string | undefined>;

Token Management Examples:

// Custom token provider (e.g., from external auth system)
kcAdminClient.registerTokenProvider({
  getAccessToken: async () => {
    // Fetch token from your auth system
    const response = await fetch("/api/keycloak-token");
    const { token } = await response.json();
    return token;
  },
});

// Manual token management
const externalToken = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...";
kcAdminClient.setAccessToken(externalToken);

// Check current token
const currentToken = await kcAdminClient.getAccessToken();
if (!currentToken) {
  // Re-authenticate if needed
  await kcAdminClient.auth(credentials);
}

Configuration Management

Runtime configuration updates and request customization.

/**
 * Update client configuration at runtime
 * @param connectionConfig - New connection configuration
 */
setConfig(connectionConfig: ConnectionConfig): void;

/**
 * Get current request options for HTTP calls
 * @returns Current RequestInit options or undefined
 */
getRequestOptions(): RequestInit | undefined;

/**
 * Get global request argument options
 * @returns Current request argument options or undefined
 */
getGlobalRequestArgOptions(): Pick<RequestArgs, "catchNotFound"> | undefined;

Configuration Examples:

// Update configuration at runtime
kcAdminClient.setConfig({
  baseUrl: "https://new-keycloak-server.com",
  realmName: "production-realm",
  requestOptions: {
    timeout: 30000,
    headers: {
      "X-Request-ID": generateRequestId(),
    },
  },
});

// Check current configuration
const requestOptions = kcAdminClient.getRequestOptions();
const argOptions = kcAdminClient.getGlobalRequestArgOptions();

Authentication Response

Token response structure returned by the authentication process.

/**
 * Response from successful authentication containing tokens and metadata
 */
interface TokenResponse {
  /** JWT access token for API authentication */
  accessToken: string;
  /** Token expiration time in seconds */
  expiresIn: string;
  /** Refresh token expiration time in seconds */
  refreshExpiresIn: number;
  /** Refresh token for obtaining new access tokens */
  refreshToken: string;
  /** Token type (typically "Bearer") */
  tokenType: string;
  /** Not-before policy timestamp */
  notBeforePolicy: number;
  /** Session state identifier */
  sessionState: string;
  /** OAuth2 scope granted */
  scope: string;
  /** Optional OpenID Connect ID token */
  idToken?: string;
}

Error Handling

The client automatically handles authentication errors and token expiration.

try {
  await kcAdminClient.auth({
    username: "invalid-user",
    password: "wrong-password",
    grantType: "password",
    clientId: "admin-cli",
  });
} catch (error) {
  if (error instanceof NetworkError) {
    // Handle authentication failure
    console.log("Authentication failed:", error.response.status);
    console.log("Error details:", error.responseData);
  }
}

docs

attack-detection.md

authentication-management.md

cache-management.md

client-configuration.md

client-management.md

client-policies.md

client-scopes.md

components.md

group-management.md

identity-providers.md

index.md

organization-management.md

realm-management.md

role-management.md

server-info.md

user-management.md

user-storage-provider.md

utility-functions.md

whoami.md

tile.json