UNPKG

@shane32/msoauth

Version:

A React library for Azure AD authentication with PKCE (Proof Key for Code Exchange) flow support. This library provides a secure and easy-to-use solution for implementing Azure AD authentication in React applications, with support for both API and Microso

204 lines (203 loc) 8.47 kB
import { TokenResponse, UserInfo } from "./AuthManager.helpers"; import OpenIDConfigurationManager from "./OpenIDConfigurationManager"; /** Types of authentication events that can be listened to */ export type AuthEventType = "login" | "logout" | "tokensChanged"; /** Callback function type for auth event listeners */ export type AuthEventListener = () => void; /** Callback function type for navigation */ export type NavigateCallback = ( /** The relative path to navigate to (must start with '/') */ path: string) => void; /** Type for policy functions that evaluate user roles */ export type PolicyFunction = (roles: string[]) => boolean; /** * Represents a set of OAuth scopes with a name */ export interface ScopeSet { /** Name of the scope set */ name: string; /** Space-delimited string of OAuth scopes */ scopes: string; } /** * Configuration object for AuthManager */ export interface AuthManagerConfiguration<TPolicyNames extends string = string> { /** Provider ID (optional, defaults to "default") */ id?: string; /** OAuth client ID */ clientId: string; /** Base URL of the OAuth authority */ authority: string; /** OAuth scopes requested (for backward compatibility, used as default scope set) */ scopes: string; /** Additional named scope sets */ scopeSets?: ScopeSet[]; /** URI where the OAuth provider will redirect after login */ redirectUri: string; /** Function to handle navigation in the app */ navigateCallback: NavigateCallback; /** Object containing policy functions for authorization */ policies: Record<TPolicyNames, PolicyFunction>; /** Optional URI for redirect after logout */ logoutRedirectUri?: string; } /** * Manages OAuth authentication flow, token handling, and user authorization. * Implements PKCE (Proof Key for Code Exchange) for secure authorization code flow. * @template TPolicyNames - Enum type for policy keys */ declare class AuthManager<TPolicyNames extends string = string> { private readonly tokenKey; private readonly verifierKey; private readonly stateKey; private readonly originalUrlKey; readonly id: string; private tokenInfo; private refreshPromise; private eventListeners; protected configManager: OpenIDConfigurationManager; private readonly absoluteRedirectUri; private readonly absoluteLogoutRedirectUri; private readonly policies; private readonly defaultScopes; private readonly allScopes; private readonly scopeSets; private readonly clientId; private readonly navigateCallback; userInfo: UserInfo | null; /** * Creates a new instance of AuthManager * @param {AuthManagerConfiguration} config - Configuration object for the AuthManager */ constructor(config: string extends TPolicyNames ? Omit<AuthManagerConfiguration<TPolicyNames>, "policies"> | AuthManagerConfiguration<TPolicyNames> : AuthManagerConfiguration<TPolicyNames>); /** * Registers an event listener for authentication events * @param {AuthEventType} event - Type of event to listen for * @param {AuthEventListener} listener - Callback function to execute */ addEventListener(event: AuthEventType, listener: AuthEventListener): void; /** * Removes an event listener for authentication events * @param {AuthEventType} event - Type of event to stop listening for * @param {AuthEventListener} listener - Callback function to remove */ removeEventListener(event: AuthEventType, listener: AuthEventListener): void; /** * Triggers an authentication event * @param {AuthEventType} event - Type of event to emit */ private emitEvent; /** * When logged in, refreshes the access token if it's expired, otherwise logs out */ autoLogin(): Promise<void>; /** * Checks if the user is currently authenticated * @returns {boolean} True if user has valid refresh tokens */ isAuthenticated(): boolean; /** * Initiates the OAuth login flow with PKCE * Redirects to the OAuth provider's authorization endpoint * @param {string} [path] - Optional path to redirect after login */ login(path?: string): Promise<void>; /** * Generates the parameters for the login request * @param {string} codeChallenge - The PKCE code challenge * @param {string} state - The state parameter for CSRF protection * @returns {URLSearchParams} The parameters for the login request * @protected */ protected generateLoginParams(codeChallenge: string, state: string): URLSearchParams; /** * Handles the OAuth redirect callback * Exchanges the authorization code for tokens * If multiple scope sets exist, immediately refreshes tokens to get tokens for all scope sets * If only one scope set exists, uses the returned tokens directly * @throws {Error} If authorization code is missing or invalid */ handleRedirect(): Promise<void>; /** * Initiates the logout process * Clears local tokens and optionally redirects to the OAuth provider's logout endpoint * @param {string} [path] - Optional path to redirect after logout */ logout(path?: string): Promise<void>; /** * Handles the redirect after logout * Restores the original URL or navigates to home */ handleLogoutRedirect(): void; /** * Performs local logout by clearing tokens and cache without redirecting to the authentication provider */ localLogout(): void; /** * Gets a valid access token for the specified scope set * @param {string} [scopeSetName="default"] - The name of the scope set to get the token for * @returns {Promise<string>} A valid access token * @throws {Error} If not authenticated, token refresh fails, or scope set doesn't exist */ getAccessToken(scopeSetName?: string): Promise<string>; /** * Gets a valid ID token, refreshing if necessary * @returns {Promise<string>} A valid ID token * @throws {Error} If not authenticated or token refresh fails */ getIdToken(): Promise<string>; /** * Refreshes all access tokens using the refresh token, * allowing simultaneous calls to avoid multiple refreshes. * A single call to refreshTokensInternal will be made, if needed. * @param {string} [refreshToken] - Optional refresh token to use * @throws {Error} If token refresh fails */ private refreshTokens; /** * Refreshes all access tokens using the refresh token * @param {string} [refreshToken] - Optional refresh token to use * @throws {Error} If token refresh fails */ protected refreshTokensInternal(refreshToken?: string): Promise<void>; /** * Checks if any access token is expired * @returns {boolean} True if any token is expired or close to expiring */ private isTokenExpired; /** * Checks if the ID token is expired * @returns {boolean} True if ID token is expired or close to expiring */ private isIdTokenExpired; /** * Checks if the user has a specific policy permission * @param {TPolicyNames} policy - The policy to check * @returns {boolean} True if user has the specified policy permission */ can(policy: TPolicyNames): boolean; /** * Gets the token endpoint URL for a specific grant type * @param {string} grantType - The OAuth grant type (e.g., "authorization_code", "refresh_token") * @returns {Promise<string>} The URL to use for token requests * @protected */ protected getTokenEndpointUrl(grantType: string): Promise<string>; /** * Generates the parameters for the token request during redirect handling * @param {string} code - The authorization code from the OAuth provider * @param {string} codeVerifier - The PKCE code verifier * @returns {URLSearchParams} The parameters for the token request * @protected */ protected generateRedirectParams(code: string, codeVerifier: string): URLSearchParams; /** * Parses the token response from the OAuth provider * @param {TokenResponse} response - The raw token response from the OAuth provider * @returns {TokenResponse} The parsed token response * @protected */ protected parseTokenResponse(response: TokenResponse): TokenResponse; } export default AuthManager;