AuthApi class
Manages all authentication-related API interactions.
Constructors
| Auth |
Methods
| 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. Example
|
| exchange |
Exchanges a verification code for access and refresh tokens. This is the second step of the magic link authentication flow. Called after the user clicks the magic link and is redirected back to your application with a verification code. Uses PKCE: the codeVerifier must match the codeChallenge sent during sendMagicLink. The redirectUri must also match the one sent during sendMagicLink. Example
|
| get |
Fetches auth settings from the backend project configuration. Use this to dynamically configure UI based on enabled auth methods. This endpoint is public and does not require authentication. Example
|
| 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 issued by the authorization server. Follows RFC 7517 (JSON Web Key) and OpenID Connect Discovery standards. Example
|
| refresh |
Refreshes an access token using a refresh token (OAuth 2.0 Refresh Token Grant per RFC 6749 Section 6). 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. For security, always returns success to prevent email enumeration attacks. 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. For security, always returns success to prevent email enumeration. Example
|
| send |
Sends a magic link email for passwordless authentication. This initiates the magic link authentication flow. The user will receive an email with a link containing a verification code and state parameter. When clicked, the link redirects to the specified redirect URI with the code and state as query parameters. PKCE is used to protect the flow: the codeChallenge is sent with this request, and the corresponding codeVerifier must be provided when exchanging the code for tokens. Example
|
| set |
Attaches a dynamic access token provider used to populate the
|
| set |
Attaches an automatic token refresh callback invoked on |
| sign |
Authenticates a user with email and password using OAuth 2.1 password grant (ROPC). Returns an access token (JWT signed with asymmetric keys) and optionally a refresh token. Example
|
| sign |
Revokes an access token (OAuth 2.0 Token Revocation per RFC 7009). The client must be authenticated using the Authorization header. Returns success regardless of token validity (per RFC 7009). 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, clients must call signIn() to obtain an access token. This design supports future email verification flows where token issuance occurs only after email verification is complete. Example
|
| 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 and they can sign in. Example
|
Constructor Details
AuthApi(ApiClient)
new AuthApi(apiClient: ApiClient)
Parameters
- apiClient
- ApiClient
An instance of ApiClient configured for your service.
Method Details
completePasswordReset(CompletePasswordResetRequest)
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.
Example
// Extract token from URL query parameter
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
if (token) {
const result = await authApi.completePasswordReset({
token,
newPassword: 'newSecurePassword123'
});
console.log(result.message); // "Password updated successfully."
}
function completePasswordReset(request: CompletePasswordResetRequest): Promise<PasswordResetResponse>
Parameters
- request
- CompletePasswordResetRequest
The reset completion request with token and new password.
Returns
Promise<PasswordResetResponse>
A promise that resolves with a success message.
exchangeVerificationCode(VerificationCodeExchangeRequest)
Exchanges a verification code for access and refresh tokens.
This is the second step of the magic link authentication flow. Called after the user clicks the magic link and is redirected back to your application with a verification code.
Uses PKCE: the codeVerifier must match the codeChallenge sent during sendMagicLink. The redirectUri must also match the one sent during sendMagicLink.
Example
const tokenResponse = await authApi.exchangeVerificationCode({
verificationCode: 'abc123...',
codeVerifier: 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk',
redirectUri: 'https://myapp.com/auth/callback'
});
console.log('Access token:', tokenResponse.accessToken);
function exchangeVerificationCode(request: VerificationCodeExchangeRequest): Promise<TokenResponse>
Parameters
- request
- VerificationCodeExchangeRequest
The exchange request with verificationCode, codeVerifier, and redirectUri.
Returns
Promise<TokenResponse>
A promise that resolves with the OAuth 2.1 token response.
getAuthSettings()
Fetches auth settings from the backend project configuration. Use this to dynamically configure UI based on enabled auth methods.
This endpoint is public and does not require authentication.
Example
const settings = await authApi.getAuthSettings();
// Check available methods
if (settings.password.enabled) {
// Show password login form
}
if (settings.passwordless.magicLink.enabled) {
// Show magic link option
}
// Or use the convenience array
settings.availableMethods.forEach(method => {
console.log(`${method} is available`);
});
function getAuthSettings(): Promise<AuthSettingsConfig>
Returns
Promise<AuthSettingsConfig>
A promise that resolves with the auth settings configuration.
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 issued by the authorization server. Follows RFC 7517 (JSON Web Key) and OpenID Connect Discovery standards.
Example
const jwks = await authApi.getJwks();
console.log('Public keys:', jwks.keys);
// Example key structure for ES256:
// {
// kty: "EC",
// use: "sig",
// kid: "rayfin-key-2024",
// alg: "ES256",
// crv: "P-256",
// x: "...",
// y: "..."
// }
function getJwks(): Promise<JwksResponse>
Returns
Promise<JwksResponse>
A promise that resolves with the JWKS containing public keys.
refreshToken(string)
Refreshes an access token using a refresh token (OAuth 2.0 Refresh Token Grant per RFC 6749 Section 6).
Example
const tokenResponse = await authApi.refreshToken(storedRefreshToken);
console.log('New access token:', tokenResponse.accessToken);
function refreshToken(refreshToken: string): Promise<TokenResponse>
Parameters
- refreshToken
-
string
The refresh token to use for obtaining a new access token.
Returns
Promise<TokenResponse>
A promise that resolves with the new token response.
requestPasswordReset(PasswordResetRequest)
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. For security, always returns success to prevent email enumeration attacks.
Example
const result = await authApi.requestPasswordReset({ email: 'user@example.com' });
console.log(result.message); // "If an account exists with this email, a reset link has been sent."
function requestPasswordReset(request: PasswordResetRequest): Promise<PasswordResetResponse>
Parameters
- request
- PasswordResetRequest
The password reset request with email address.
Returns
Promise<PasswordResetResponse>
A promise that resolves with a success message.
resendVerificationEmail(ResendVerificationEmailRequest)
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. For security, always returns success to prevent email enumeration.
Example
const result = await authApi.resendVerificationEmail({ email: 'user@example.com' });
console.log(result.message); // "If an account exists with this email and is unverified, a verification link has been sent."
function resendVerificationEmail(request: ResendVerificationEmailRequest): Promise<ResendVerificationEmailResponse>
Parameters
- request
- ResendVerificationEmailRequest
The resend request with email address.
Returns
Promise<ResendVerificationEmailResponse>
A promise that resolves with a success message.
sendMagicLink(MagicLinkRequest)
Sends a magic link email for passwordless authentication.
This initiates the magic link authentication flow. The user will receive an email with a link containing a verification code and state parameter. When clicked, the link redirects to the specified redirect URI with the code and state as query parameters.
PKCE is used to protect the flow: the codeChallenge is sent with this request, and the corresponding codeVerifier must be provided when exchanging the code for tokens.
Example
const response = await authApi.sendMagicLink({
email: 'user@example.com',
codeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM',
state: 'xyzzy123',
redirectUri: 'https://myapp.com/auth/callback'
});
console.log(response.success); // true
function sendMagicLink(request: MagicLinkRequest): Promise<MagicLinkResponse>
Parameters
- request
- MagicLinkRequest
The magic link request with email, codeChallenge, state, and redirectUri.
Returns
Promise<MagicLinkResponse>
A promise that resolves with success status.
setAccessTokenProvider(() => null | string)
Attaches a dynamic access token provider used to populate the
Authorization header on outgoing requests. Used by Auth to keep
the access token concealed.
function setAccessTokenProvider(provider: () => null | string)
Parameters
- provider
-
() => null | string
Function returning the current access token, or null when signed out.
setRefreshCallback(() => Promise<void>)
Attaches an automatic token refresh callback invoked on 401 responses
before the request is retried. Used by Auth for transparent
session refresh.
function setRefreshCallback(callback: () => Promise<void>)
Parameters
- callback
-
() => Promise<void>
Async function that refreshes the session.
signIn(PasswordGrantCredentials)
Authenticates a user with email and password using OAuth 2.1 password grant (ROPC).
Returns an access token (JWT signed with asymmetric keys) and optionally a refresh token.
Example
const tokenResponse = await authApi.signIn({
email: 'user@example.com',
password: 'password123'
});
console.log('Access token:', tokenResponse.accessToken);
console.log('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(string)
Revokes an access token (OAuth 2.0 Token Revocation per RFC 7009).
The client must be authenticated using the Authorization header. Returns success regardless of token validity (per RFC 7009).
Example
await authApi.signOut(accessToken);
console.log('Token revoked successfully');
function signOut(token: string): Promise<void>
Parameters
- token
-
string
The access token to revoke. If not provided, uses the current authenticated token.
Returns
Promise<void>
A promise that resolves when signout is complete.
signOutAll(string)
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 authApi.signOutAll(accessToken);
console.log(`Revoked ${result.count} sessions`);
function signOutAll(bearerToken: string): Promise<SignOutAllResponse>
Parameters
- bearerToken
-
string
The current access token for authentication.
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, clients must call signIn() to obtain an access token. This design supports future email verification flows where token issuance occurs only after email verification is complete.
Example
// Step 1: Sign up
const signupResponse = await authApi.signUp({ email: 'user@example.com', password: 'password123' });
console.log('User created:', signupResponse.userId);
// Step 2: Sign in to get access token
const tokenResponse = await authApi.signIn({ email: 'user@example.com', password: 'password123' });
console.log('Access token:', tokenResponse.accessToken);
function signUp(credentials: SignUpCredentials): Promise<SignUpResponse>
Parameters
- credentials
- SignUpCredentials
The email and password for the new user.
Returns
Promise<SignUpResponse>
A promise that resolves with the signup response (userId, email, role, createdAt).
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 and they can sign in.
Example
// Extract token from URL query parameter
const urlParams = new URLSearchParams(window.location.search);
const token = urlParams.get('token');
if (token) {
const result = await authApi.verifyEmail(token);
console.log(result.message); // "Email verified successfully!"
}
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.