import { LitElement } from 'lit'; import { KeycloakOnLoad } from 'keycloak-js'; import { AuthState } from './kc-context.js'; import { KeycloakError } from '../../errors/keycloak-errors.js'; import { ErrorLogger } from '../../errors/error-logger.js'; /** * Event detail types for custom events */ export interface KcErrorDetail { error: KeycloakError; timestamp: number; canRetry: boolean; } export interface KcRetryDetail { attempt: number; maxAttempts: number; delay: number; error: unknown; } export interface KcStateChangeDetail { previous: AuthState; current: AuthState; } /** * Initializes Keycloak authentication and provides auth context to child components. * * This component must be placed at the root of your application to enable authentication. * All child components can access the auth state through Lit context. The provider handles * the complete authentication lifecycle including initialization, token refresh, and logout. * * @element kc-provider * * @attr {string} url - Keycloak server URL (e.g., "https://keycloak.example.com/" or "https://keycloak.example.com/auth/" for older versions) * @attr {string} realm - Keycloak realm name * @attr {string} client-id - Client ID registered in Keycloak * @attr {string} [scope] - Optional OAuth scopes (space-separated, e.g., "openid profile email") * @attr {string} [on-load="check-sso"] - Initialization behavior: "check-sso" (silent check) or "login-required" (force login) * @attr {boolean} [use-nonce] - Enable nonce validation for enhanced security (omit for Keycloak default) * @attr {string} [adapter] - Keycloak adapter type: "default", "cordova", or "cordova-native" * @attr {boolean} [check-login-iframe] - Enable iframe-based session checking (omit for Keycloak default) * @attr {number} [check-login-iframe-interval] - Iframe check interval in seconds (default: 5) * @attr {string} [response-mode] - OAuth response mode: "query" or "fragment" * @attr {string} [redirect-uri] - Custom redirect URI after login (defaults to current URL) * @attr {string} [silent-check-sso-redirect-uri] - URI for silent SSO check iframe * @attr {boolean} [silent-check-sso-fallback] - Enable fallback if silent SSO fails * @attr {string} [flow] - OAuth flow: "standard" (authorization code), "implicit", or "hybrid" * @attr {string} [pkce-method] - PKCE method: "S256" (recommended) or "false" to disable * @attr {boolean} [enable-logging] - Enable Keycloak debug logging to console * @attr {number} [message-receive-timeout] - Timeout for iframe messages in milliseconds * @attr {string} [locale] - Preferred locale for Keycloak UI (e.g., "en", "de", "fr") * @attr {string} [logout-method] - HTTP method for logout: "GET" or "POST" * * @prop {string} [token] - JWT access token (can be set programmatically to restore session) * @prop {string} [refreshToken] - JWT refresh token (can be set programmatically to restore session) * @prop {string} [idToken] - JWT ID token (can be set programmatically to restore session) * @prop {number} [timeSkew] - Time difference between local and server in seconds * * @fires {CustomEvent} auth-success - Fired when authentication succeeds (via Keycloak.onAuthSuccess) * @fires {CustomEvent} auth-error - Fired when authentication fails (via Keycloak.onAuthError) * @fires {CustomEvent} auth-refresh-success - Fired when token refresh succeeds * @fires {CustomEvent} auth-refresh-error - Fired when token refresh fails * @fires {CustomEvent} auth-logout - Fired when user logs out * @fires {CustomEvent} token-expired - Fired when token expires * * @example Basic setup with check-sso * ```html * * *

Welcome, authenticated user!

*
* * * * * *
* ``` * * @example Force login on page load * ```html * * *

Protected Application

*
*
* ``` * * @example Programmatic token restoration * ```typescript * const provider = document.querySelector('kc-provider'); * // Restore from localStorage or secure storage * provider.token = savedToken; * provider.refreshToken = savedRefreshToken; * provider.idToken = savedIdToken; * ``` * * @example With custom scopes and PKCE * ```html * * * * ``` */ export declare class KcProvider extends LitElement { /** * Keycloak server URL. Must include protocol and trailing slash. * For Keycloak 17+, typically just the base URL (e.g., "https://keycloak.example.com/"). * For older versions, include "/auth/" path (e.g., "https://keycloak.example.com/auth/"). * * @default "http://localhost:8080/" */ url: string; /** * Keycloak realm name. Must match an existing realm in your Keycloak instance. * * @default "master" */ realm: string; /** * Client ID registered in Keycloak. Must be a public client configured for your application. * Ensure "Valid Redirect URIs" and "Web Origins" are properly configured in Keycloak. * * @required */ clientId: string; /** * OAuth scopes to request (space-separated). Common scopes include: * - "openid" - Required for OIDC * - "profile" - User profile information * - "email" - User email address * - "roles" - User roles * * @example "openid profile email" */ scope?: string; /** * Initialization behavior when the page loads: * - "check-sso" - Silently check if user is already authenticated (recommended for SPAs) * - "login-required" - Force login redirect if not authenticated * * @default "check-sso" */ onLoad: KeycloakOnLoad; /** * Enable nonce validation for enhanced security against replay attacks. * Omit to use Keycloak's default behavior. */ useNonce?: boolean; /** * Keycloak adapter type for different platforms: * - "default" - Standard web browser * - "cordova" - Apache Cordova/PhoneGap * - "cordova-native" - Cordova with native browser */ adapter?: "default" | "cordova" | "cordova-native"; /** * Enable iframe-based session checking to detect logout in other tabs. * Omit to use Keycloak's default behavior (typically enabled). */ checkLoginIframe?: boolean; /** * Interval in seconds for checking session status via iframe. * Lower values provide faster logout detection but increase server load. * * @default 5 */ checkLoginIframeInterval?: number; /** * OAuth response mode for authorization code: * - "query" - Parameters in query string * - "fragment" - Parameters in URL fragment (more secure for SPAs) */ responseMode?: "query" | "fragment"; /** * Custom redirect URI after login. Defaults to current page URL. * Must match one of the "Valid Redirect URIs" in Keycloak client settings. */ redirectUri?: string; /** * URI for the silent SSO check iframe. Used when on-load="check-sso". * Should be a minimal HTML page that loads Keycloak. */ silentCheckSsoRedirectUri?: string; /** * Enable fallback to regular login if silent SSO check fails. * Useful for handling third-party cookie blocking. */ silentCheckSsoFallback?: boolean; /** * OAuth 2.0 flow type: * - "standard" - Authorization Code Flow (recommended, most secure) * - "implicit" - Implicit Flow (legacy, less secure) * - "hybrid" - Hybrid Flow (combination of both) */ flow?: "standard" | "implicit" | "hybrid"; /** * PKCE (Proof Key for Code Exchange) method for enhanced security: * - "S256" - SHA-256 hashing (recommended) * - "false" - Disable PKCE (not recommended) * * PKCE protects against authorization code interception attacks. */ pkceMethod?: "S256" | "false"; /** * Enable Keycloak debug logging to browser console. * Useful for troubleshooting authentication issues. */ enableLogging?: boolean; /** * Timeout in milliseconds for receiving messages from iframe. * Increase if experiencing timeout errors on slow networks. * * @default 10000 */ messageReceiveTimeout?: number; /** * Preferred locale for Keycloak login and account pages. * Must be enabled in Keycloak realm settings. * * @example "en" | "de" | "fr" | "es" */ locale?: string; /** * HTTP method for logout endpoint: * - "GET" - Traditional logout (may have CSRF risks) * - "POST" - More secure logout method (recommended) */ logoutMethod?: "GET" | "POST"; /** * JWT access token. Can be set programmatically to restore a session. * Not exposed as an HTML attribute for security reasons. */ token?: string; /** * JWT refresh token. Can be set programmatically to restore a session. * Not exposed as an HTML attribute for security reasons. */ refreshToken?: string; /** * JWT ID token. Can be set programmatically to restore a session. * Not exposed as an HTML attribute for security reasons. */ idToken?: string; /** * Time difference between local and Keycloak server in seconds. * Used to adjust token expiration checks for clock skew. */ timeSkew?: number; /** * Maximum number of retry attempts for failed initialization. * Set to 1 to disable retry (single attempt only). * * @default 3 */ retryAttempts: number; /** * Initial delay in milliseconds before first retry. * Subsequent retries use exponential backoff. * * @default 1000 */ retryDelay: number; /** * Enable automatic retry on initialization failure. * If false, only one initialization attempt is made. * * @default true */ autoRetry: boolean; /** * Callback function called when an error occurs. * Receives the wrapped KeycloakError with user-friendly messages. */ onError?: (error: KeycloakError) => void; /** * Callback function called when a retry attempt is made. */ onRetry?: (detail: KcRetryDetail) => void; /** * Callback function called when auth state changes. */ onStateChange?: (detail: KcStateChangeDetail) => void; /** * Error logger instance for logging errors. * Defaults to console logger if not provided. */ errorLogger?: ErrorLogger; authData: AuthState; private initAttempt; private isRetrying; /** * Get the error logger instance (use default if not set) */ private getErrorLogger; /** * Dispatch error event and call error callback */ private dispatchError; /** * Dispatch state change event and call state change callback */ private dispatchStateChange; /** * Update auth data and dispatch events */ private updateAuthData; /** * Sleep for specified milliseconds */ private sleep; /** * Initialize Keycloak with retry logic */ private initWithRetry; /** * Manually retry initialization */ retry(): Promise; /** * Builds Keycloak initialization options from component properties. * Only includes options that have been explicitly set to avoid overriding Keycloak defaults. * * @private * @returns {KeycloakInitOptions} Configuration object for Keycloak.init() */ private buildInitOptions; /** * Lifecycle method called after the first render. * Initializes Keycloak instance and sets up event handlers for auth state changes. * * @private */ firstUpdated(): Promise; /** * Renders the component's slot to display child components. * The slot allows any child components to access the auth context. */ render(): import('lit').TemplateResult<1>; } //# sourceMappingURL=kc-provider.d.ts.map