Auth class
The main Auth module class. This provides the high-level API for authentication operations and manages the user session.
Constructors
| Auth(Api |
Methods
| attach |
Attaches authorization header injection and automatic token refresh to another <xref:ApiClient> instance, so requests made through it carry the current access token and trigger a refresh on 401 responses. |
| complete |
Completes the password reset process with a reset token and new password. This method is called after a user clicks the reset link in their email and submits a new password. Upon success, all existing sessions are invalidated for security and the user must sign in with the new password. Emits Example
|
| destroy() | Cleans up resources used by the Auth instance.
Removes storage event listener and clears timers.
New or queued refreshes reject with |
| get |
Returns the internal AuthApi instance. Used by companion auth provider packages (e.g., fabric provider). |
| get |
Gets the authentication settings from the backend. This is a public endpoint that does not require authentication. Example
|
| get |
Returns the validated claims from the current access token without exposing the token itself. Custom claims generated for the application are declaration-merged into
the returned |
| get |
Retrieves the JSON Web Key Set (JWKS) containing public keys for JWT verification. This endpoint provides public keys used to verify JWT access tokens and refresh tokens issued by the authorization server. Follows RFC 7517 (JSON Web Key) and OpenID Connect Discovery standards. The response may contain multiple keys to support key rotation:
Use the Example
|
| get |
Extracts the verification code from a magic link callback URL. |
| get |
Returns the current authenticated session. |
| handle |
Handles the callback from a magic link authentication flow. This method extracts the verification code and state from the URL, retrieves the stored PKCE verifier, and exchanges the code for tokens. On success, a session is created and the user is authenticated. Emits Example
|
| has |
Returns true if the current session has a refresh token available. |
| is |
Checks if the current URL appears to be a magic link callback. This is a quick check to determine if the current page load is from
a magic link click. Use Example
|
| on(Auth |
Subscribes to a specific authentication event. |
| on |
Primary event listener for session changes (PRD-aligned method name). Fires on: SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, etc. |
| refresh |
Refreshes the current session using the stored refresh token. Uses a promise lock to prevent concurrent refresh requests. Example
|
| request |
Requests a password reset email for the specified email address. This initiates the password reset flow. If an account exists with the provided email, a reset link will be sent to that address. For security, always returns success to prevent email enumeration attacks. Emits Example
|
| resend |
Resends the email verification link to the specified email address. This allows users to request a new verification email if they didn't receive the original or if it expired. Previous unused verification tokens are automatically invalidated when a new one is generated. For security, always returns success to prevent email enumeration attacks. Emits Example
|
| send |
Initiates a magic link authentication flow. This method generates PKCE parameters, stores the code verifier in localStorage, and sends a magic link email to the specified address. When the user clicks the link, they will be redirected to your application with a verification code and state parameter. Use Emits Example
|
| sign |
Signs in a user with email and password using OAuth 2.1 password grant (ROPC). After successful signin, the user session will be stored internally. Returns an access token (JWT signed with asymmetric keys) and optionally a refresh token. Example
|
| sign |
Signs out the current user by revoking their access token (OAuth 2.0 Token Revocation). Clears the internal session and revokes the token on the server. Per RFC 7009, the server returns success regardless of token validity. Example
|
| sign |
Revokes all active sessions for the authenticated user. This invalidates all tokens issued to the user, forcing re-authentication. Useful for security incidents or password changes. Example
|
| sign |
Registers a new user with email and password. After successful signup, you must call signIn() to obtain an access token. This design supports future email verification flows. Emits Example
|
| start |
Starts automatic token refresh scheduling. Re-enables the session expiration timer and triggers an immediate refresh if the current access token is expired or near-expiry. Only meaningful when Example React Native AppState integration
|
| stop |
Stops automatic token refresh scheduling.
Cancels any pending session expiration timer so no automatic refresh occurs
until Only meaningful when |
| verify |
Verifies a user's email address with a verification token. This method is called after a user clicks the verification link in their email. Upon success, the user's email is marked as verified. The user must then sign in to obtain an access token. Emits Example
|
Constructor Details
Auth(ApiClient, AuthOptions)
new Auth(apiClient: ApiClient, options?: AuthOptions)
Parameters
- apiClient
- ApiClient
An instance of ApiClient to be used by the AuthApi.
- options
- AuthOptions
Method Details
attachToClient(ApiClient)
Attaches authorization header injection and automatic token refresh to another <xref:ApiClient> instance, so requests made through it carry the current access token and trigger a refresh on 401 responses.
function attachToClient(client: ApiClient)
Parameters
- client
- ApiClient
The API client to wire up with this Auth instance.
completePasswordReset(string, string)
Completes the password reset process with a reset token and new password.
This method is called after a user clicks the reset link in their email and submits a new password. Upon success, all existing sessions are invalidated for security and the user must sign in with the new password.
Emits AUTH_PASSWORD_RESET_COMPLETED event on success.
Example
// Listen for password reset completion events
auth.on('AUTH_PASSWORD_RESET_COMPLETED', () => {
console.log('Password reset complete! Please sign in with new password.');
});
// Extract token from URL query parameter
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
if (token) {
try {
// newPassword is collected from your reset-password form
const result = await auth.completePasswordReset(token, newPassword);
console.log(result.message); // "Password updated successfully."
} catch (error) {
console.error('Password reset failed:', error.message);
}
}
function completePasswordReset(token: string, newPassword: string): Promise<PasswordResetResponse>
Parameters
- token
-
string
The reset token from the email link.
- newPassword
-
string
The new password to set.
Returns
Promise<PasswordResetResponse>
A promise that resolves with a success message.
destroy()
Cleans up resources used by the Auth instance.
Removes storage event listener and clears timers.
New or queued refreshes reject with AUTH_DESTROYED. Already-issued
refreshes may finish and persist rotated credentials without rearming
timers. This does not sign out or wait for pending storage writes.
Should be called when the Auth instance is no longer needed.
function destroy()
getAuthApi()
Returns the internal AuthApi instance. Used by companion auth provider packages (e.g., fabric provider).
function getAuthApi(): AuthApi
Returns
The AuthApi instance used by this Auth instance.
getAuthSettings()
Gets the authentication settings from the backend. This is a public endpoint that does not require authentication.
Example
const settings = await auth.getAuthSettings();
if (settings.password.enabled) {
// Show password login form
}
if (settings.passwordless.magicLink.enabled) {
// Show magic link option
}
function getAuthSettings(): Promise<AuthSettingsConfig>
Returns
Promise<AuthSettingsConfig>
A promise that resolves with the authentication configuration.
getClaims()
Returns the validated claims from the current access token without exposing the token itself.
Custom claims generated for the application are declaration-merged into
the returned ClientClaims type. Tokens carry every custom claim as a
string, so each one is typed string here (a provider's false arrives
as 'false'). Server-side policies and a function's ctx.getClaims()
see the declared types.
function getClaims(): Promise<ClientClaims>
Returns
Promise<ClientClaims>
The base and application-defined claims for the current session.
getJwks()
Retrieves the JSON Web Key Set (JWKS) containing public keys for JWT verification.
This endpoint provides public keys used to verify JWT access tokens and refresh tokens issued by the authorization server. Follows RFC 7517 (JSON Web Key) and OpenID Connect Discovery standards.
The response may contain multiple keys to support key rotation:
- Active key: The current signing key used for new tokens
- Previous key: The previous signing key for validating tokens signed before rotation
Use the kid (key ID) from the JWT header to find the matching verification key.
Example
const jwks = await auth.getJwks();
console.log('Public keys:', jwks.keys);
// Find key by kid
const key = jwks.keys.find(k => k.kid === 'desired-kid');
function getJwks(): Promise<JwksResponse>
Returns
Promise<JwksResponse>
A promise that resolves with the JWKS containing public keys.
getMagicLinkVerificationCode(string)
Extracts the verification code from a magic link callback URL.
function getMagicLinkVerificationCode(url?: string): string | null
Parameters
- url
-
string
Optional URL to parse. Defaults to window.location.href.
Returns
string | null
The verification code or null if not present.
getSession()
Returns the current authenticated session.
function getSession(): OpaqueSession
Returns
The current session object or null if no user is authenticated.
handleMagicLinkCallback(string)
Handles the callback from a magic link authentication flow.
This method extracts the verification code and state from the URL, retrieves the stored PKCE verifier, and exchanges the code for tokens. On success, a session is created and the user is authenticated.
Emits AUTH_LOGIN on success.
Example
// In your callback page/route
const result = await auth.handleMagicLinkCallback();
if (result.success) {
console.log('Authenticated!', result.session);
// Redirect to app
} else {
console.error('Authentication failed:', result.error);
// Show error message
}
function handleMagicLinkCallback(url?: string): Promise<MagicLinkCallbackResult>
Parameters
- url
-
string
Optional URL to parse. Defaults to window.location.href.
Returns
Promise<MagicLinkCallbackResult>
A promise that resolves with the callback result.
hasRefreshToken()
Returns true if the current session has a refresh token available.
function hasRefreshToken(): boolean
Returns
boolean
True if refresh token exists and session is active.
isMagicLinkCallback(string)
Checks if the current URL appears to be a magic link callback.
This is a quick check to determine if the current page load is from
a magic link click. Use handleMagicLinkCallback() to actually process it.
Example
// On app initialization
if (auth.isMagicLinkCallback()) {
const result = await auth.handleMagicLinkCallback();
// Handle result...
}
function isMagicLinkCallback(url?: string): boolean
Parameters
- url
-
string
Optional URL to check. Defaults to window.location.href.
Returns
boolean
True if the URL contains magic link callback parameters.
on(AuthEvent, (session: OpaqueSession) => void)
Subscribes to a specific authentication event.
function on(event: AuthEvent, handler: (session: OpaqueSession) => void): () => void
Parameters
- event
- AuthEvent
The auth event to listen for (e.g. AUTH_LOGIN, AUTH_LOGOUT, AUTH_REFRESH).
- handler
-
(session: OpaqueSession) => void
Callback invoked with the current session when the event fires.
Returns
() => void
A cleanup function that unsubscribes the handler.
onSessionChange((session: OpaqueSession | null) => void)
Primary event listener for session changes (PRD-aligned method name). Fires on: SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, etc.
function onSessionChange(callback: (session: OpaqueSession | null) => void): () => void
Parameters
- callback
-
(session: OpaqueSession | null) => void
Function called with session or null
Returns
() => void
Cleanup function to unsubscribe
refreshSession({ signal?: AbortSignal, timeout?: number })
Refreshes the current session using the stored refresh token. Uses a promise lock to prevent concurrent refresh requests.
Example
try {
const tokens = await auth.refreshSession();
console.log('Session refreshed:', tokens);
} catch (error) {
console.error('Refresh failed:', error);
}
function refreshSession(opts?: { signal?: AbortSignal, timeout?: number }): Promise<TokenResponse>
Parameters
- opts
-
{ signal?: AbortSignal, timeout?: number }
Returns
Promise<TokenResponse>
A promise that resolves with new token response.
requestPasswordReset(string)
Requests a password reset email for the specified email address.
This initiates the password reset flow. If an account exists with the provided email, a reset link will be sent to that address. For security, always returns success to prevent email enumeration attacks.
Emits AUTH_PASSWORD_RESET_REQUESTED event on success.
Example
// Listen for password reset events
auth.on('AUTH_PASSWORD_RESET_REQUESTED', () => {
console.log('Password reset email sent!');
});
try {
const result = await auth.requestPasswordReset('user@example.com');
console.log(result.message);
} catch (error) {
console.error('Reset request failed:', error.message);
}
function requestPasswordReset(email: string): Promise<PasswordResetResponse>
Parameters
-
string
The email address to send the reset link to.
Returns
Promise<PasswordResetResponse>
A promise that resolves with a success message.
resendVerificationEmail(string)
Resends the email verification link to the specified email address.
This allows users to request a new verification email if they didn't receive the original or if it expired. Previous unused verification tokens are automatically invalidated when a new one is generated. For security, always returns success to prevent email enumeration attacks.
Emits AUTH_VERIFICATION_EMAIL_RESENT event on success.
Example
// Listen for resend events
auth.on('AUTH_VERIFICATION_EMAIL_RESENT', () => {
console.log('Verification email resent!');
});
try {
const result = await auth.resendVerificationEmail('user@example.com');
console.log(result.message);
} catch (error) {
console.error('Resend failed:', error.message);
}
function resendVerificationEmail(email: string): Promise<ResendVerificationEmailResponse>
Parameters
-
string
The email address to resend the verification link to.
Returns
Promise<ResendVerificationEmailResponse>
A promise that resolves with a success message.
sendMagicLink(MagicLinkOptions)
Initiates a magic link authentication flow.
This method generates PKCE parameters, stores the code verifier in localStorage, and sends a magic link email to the specified address. When the user clicks the link, they will be redirected to your application with a verification code and state parameter.
Use handleMagicLinkCallback() to complete the authentication when the user returns.
Emits AUTH_MAGIC_LINK_SENT event on success, AUTH_MAGIC_LINK_ERROR on failure.
Example
// Listen for magic link events
auth.on('AUTH_MAGIC_LINK_SENT', () => {
console.log('Magic link sent! Check your email.');
});
try {
const result = await auth.sendMagicLink({
email: 'user@example.com',
redirectUri: 'https://myapp.com/auth/callback'
});
console.log('State:', result.state); // Stored for callback correlation
} catch (error) {
console.error('Failed to send magic link:', error.message);
}
function sendMagicLink(options: MagicLinkOptions): Promise<MagicLinkResult>
Parameters
- options
- MagicLinkOptions
The magic link options (email and redirectUri).
Returns
Promise<MagicLinkResult>
A promise that resolves with the result containing the state parameter.
signIn(PasswordGrantCredentials)
Signs in a user with email and password using OAuth 2.1 password grant (ROPC).
After successful signin, the user session will be stored internally. Returns an access token (JWT signed with asymmetric keys) and optionally a refresh token.
Example
// email and password are collected from your sign-in form
const tokenResponse = await auth.signIn({ email, password });
console.log('Signed in, access token expires in:', tokenResponse.expiresIn, 'seconds');
function signIn(credentials: PasswordGrantCredentials): Promise<TokenResponse>
Parameters
- credentials
- PasswordGrantCredentials
The email and password for authentication.
Returns
Promise<TokenResponse>
A promise that resolves with the OAuth 2.1 token response.
signOut()
Signs out the current user by revoking their access token (OAuth 2.0 Token Revocation).
Clears the internal session and revokes the token on the server. Per RFC 7009, the server returns success regardless of token validity.
Example
// Listen for sign-out events to update UI
auth.on('AUTH_LOGOUT', () => {
navigate('/login');
});
try {
await auth.signOut();
// Internal session is cleared even if the server call fails.
} catch (error) {
console.error('Sign-out had a problem:', error.message);
}
function signOut(): Promise<void>
Returns
Promise<void>
A promise that resolves when signout is complete.
signOutAll()
Revokes all active sessions for the authenticated user.
This invalidates all tokens issued to the user, forcing re-authentication. Useful for security incidents or password changes.
Example
const result = await auth.signOutAll();
console.log(`Revoked ${result.count} sessions`);
function signOutAll(): Promise<SignOutAllResponse>
Returns
Promise<SignOutAllResponse>
A promise that resolves with the count of sessions revoked.
signUp(SignUpCredentials)
Registers a new user with email and password.
After successful signup, you must call signIn() to obtain an access token. This design supports future email verification flows.
Emits AUTH_SIGNUP event on success.
Example
// Listen for signup events
auth.on('AUTH_SIGNUP', (session) => {
console.log('User signed up!');
});
// email and password are collected from your sign-up form
// Step 1: Sign up
const signupResponse = await auth.signUp({ email, password });
console.log('User created:', signupResponse.userId);
// Step 2: Sign in to get access token
await auth.signIn({ email, password });
function signUp(credentials: SignUpCredentials): Promise<SignUpResponse>
Parameters
- credentials
- SignUpCredentials
The signup credentials (email, password).
Returns
Promise<SignUpResponse>
A promise that resolves with signup response (userId, email, role, createdAt).
startAutoRefresh()
Starts automatic token refresh scheduling. Re-enables the session expiration timer and triggers an immediate refresh if the current access token is expired or near-expiry.
Only meaningful when autoRefreshToken is false — gives the consumer
manual control over the refresh cycle. When autoRefreshToken is true
(default), this is a no-op.
Example
React Native AppState integration
AppState.addEventListener('change', (state) => {
state === 'active' ? auth.startAutoRefresh() : auth.stopAutoRefresh();
});
function startAutoRefresh(): Promise<void>
Returns
Promise<void>
stopAutoRefresh()
Stops automatic token refresh scheduling.
Cancels any pending session expiration timer so no automatic refresh occurs
until startAutoRefresh() is called again.
Only meaningful when autoRefreshToken is false. When autoRefreshToken
is true (default), this is a no-op.
function stopAutoRefresh()
verifyEmail(string)
Verifies a user's email address with a verification token.
This method is called after a user clicks the verification link in their email. Upon success, the user's email is marked as verified. The user must then sign in to obtain an access token.
Emits AUTH_EMAIL_VERIFIED event on success.
Example
// Listen for email verification events
auth.on('AUTH_EMAIL_VERIFIED', () => {
console.log('Email verified! You can now sign in.');
});
// Extract token from URL query parameter
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
if (token) {
try {
const result = await auth.verifyEmail(token);
console.log(result.message); // "Email verified successfully!"
} catch (error) {
console.error('Verification failed:', error.message);
}
}
function verifyEmail(token: string): Promise<EmailVerificationResponse>
Parameters
- token
-
string
The verification token from the email link.
Returns
Promise<EmailVerificationResponse>
A promise that resolves with the verification response.