Getting Started with Authentication SDK
- Prerequisites
- Getting Started
- User Management Operations
- Email Verification and Reset Password
- Third-Party Identity Providers
- Link Social Accounts
- Authentication Error Handling
- Persistence Settings
- Use MFA Through the Relational Client
- Use MFA with the JavaScript SDK
Prerequisites
Install the relational JavaScript SDK:
npm install @fusabase/fusabase-relational
This package provides the relational client, including client.auth and client.appTrust.
Register a web app and configure the project’s authentication backend before using these examples. Copy the application configuration and the schema-specific ORDS URL from the Console. Pass the URL as the first argument to createClient() and the configuration object as the second. See Adding Oracle Backend with Supabase APIs to Your Apps and Setting Up Authentication.
Getting Started
Create the relational client, then call client.auth.initialize() to wait for saved authentication state and retrieve the initial session.
import { createClient } from "@fusabase/fusabase-relational";
const client = createClient("http://localhost:8080/ords/testuser/", {
schema: "testuser",
app_name: "DDSDemoWeb",
app_type: "WEB",
app_id: "APP_ID",
objs_type: "base",
backend_type: "RELATIONAL",
project_id: "PROJECT_ID",
storage_bucket: "STORAGE_BUCKET",
auth_type: "base",
auth_id: "AUTH_ID"
});
const { error: initializationError } = await client.auth.initialize();
if (initializationError) throw initializationError;
Replace the example host, schema, app name, and service settings with the values generated by your Console. Keep the ORDS URL’s trailing / and the configuration’s backend_type: "RELATIONAL" value. Replace the following placeholders:
APP_ID: the registered web app’s ID.PROJECT_ID: the project ID.STORAGE_BUCKET: the generated storage bucket value.AUTH_ID: the project’s authentication ID.
The following snippets demonstrate separate API operations that reuse client. Use real values from your application UI or configured provider where an example requires a password, token, code, or factor ID. Signed-in operations require a current user; sign in again after using the sign-out example.
Relational authentication operations return { data, error }. Check error before using the result or treating an operation as successful. Lifecycle controls have the return contracts described in their section.
Create an email and password account with signUp():
await client.auth.signUp({
email: "ada@example.com",
password: "strong-password",
options: { data: { full_name: "Ada Lovelace" } }
});
Sign in with an email address and password:
await client.auth.signInWithPassword({
email: "ada@example.com",
password: "strong-password"
});
Check error before using the result. Authentication errors can include a message, HTTP status, and error code. For an enrolled user, complete the multi-factor sign-in challenge before treating sign-in as complete.
After sign-in, use the same client to call the database APIs. See Using Database SDK.
User Management Operations
Use getUser() to reload and return the current user profile. Use getClaims() to read claims from the current token or a supplied JWT.
const { data: { user } } = await client.auth.getUser();
const { data } = await client.auth.getClaims();
Update the current user’s display name through full_name with updateUser():
await client.auth.updateUser({ data: { full_name: "Ada Byron" } });
updateUser() can also update a password. A password update requires oldPassword. Call signOut() to sign out the current user.
await client.auth.signOut();
Email Verification and Reset Password
Use resend() to resend signup email verification for the current signed-in user:
await client.auth.resend({ type: "signup", email: "ada@example.com" });
Send a password-reset email with resetPasswordForEmail():
await client.auth.resetPasswordForEmail("ada@example.com");
Validate a password-reset code with verifyOtp(). Pass the code returned by the recovery flow as token_hash:
await client.auth.verifyOtp({ token_hash, type: "recovery" });
verifyOtp() validates the code without signing the user in or changing the password.
The relational updateUser({ password }) operation requires oldPassword and cannot complete a forgotten-password reset.
The SDK ignores redirectTo when requesting a password-reset email.
Third-Party Identity Providers
The SDK supports OAuth sign-in and direct provider-token sign-in. signInWithOAuth() redirects by default; Set options.skipBrowserRedirect to true to use a popup. Direct token requirements depend on the provider. The example in this section uses a Google ID token.
Configure providers before using them. See Setting Up Third-Party Identity Providers.
Web Sign-In Flow
Call the following function from your application’s sign-in UI to start a Google redirect flow:
async function beginGoogleSignIn() {
const { error } = await client.auth.signInWithOAuth({ provider: "google" });
if (error) throw error;
}
A successful redirect navigates away, and the initiating promise does not resolve. Do not put redirect-completion code after that awaited call in the same handler.
On the return page, initialize client as shown in Getting Started, then call getRedirectResult() during application startup:
const redirectResult = await client.auth.getRedirectResult();
if (redirectResult.error) throw redirectResult.error;
// Update your UI with redirectResult.data.user
// and redirectResult.data.session.
// Both are null when no redirect result is pending.
To exchange a Google ID token obtained through your provider integration, pass it through token:
await client.auth.signInWithIdToken({
provider: "google",
token: googleIdToken
});
Supply the provider credential through token. In this SDK implementation, setting only access_token does not send that credential. Do not assume that Google, Facebook, and GitHub supply interchangeable token types.
Link Social Accounts
For a signed-in user, use getUserIdentities() to list linked provider identities. Use linkIdentity() with a provider token obtained by your application to link an identity:
const { data } = await client.auth.getUserIdentities();
await client.auth.linkIdentity({ provider: "google", token: googleIdToken });
Unlink Social Accounts
Call unlinkIdentity() with the provider identifier, such as "google", to remove that linked identity:
await client.auth.unlinkIdentity("google");
Authentication Error Handling
Check error before using authentication data:
const { data, error } = await client.auth.signInWithPassword({
email: "ada@example.com",
password: "strong-password",
});
if (error) {
console.error(error.message, error.status, error.code);
} else {
// Update the application UI for the signed-in user.
}
Persistence Settings
initialize() waits for saved authentication state and returns the initial session. Use getSession() to retrieve the current session, refreshSession() to refresh credentials, and setSession() to restore a session from access and refresh tokens.
The SDK also provides lifecycle controls:
-
startAutoRefresh()schedules refresh for a current session. Call it after successful sign-in or session restoration:const { data, error } = await client.auth.getSession(); if (error) throw error; if (data.session) client.auth.startAutoRefresh();Calling it while signed out does not start refresh automatically when a user signs in later.
-
stopAutoRefresh()clears the currently scheduled refresh timeout:client.auth.stopAutoRefresh(); -
dispose()clears the scheduled refresh timeout and removes Auth listeners registered through this client. It does not sign the user out:await client.auth.dispose(); -
onAuthStateChange(callback)subscribes to initial, sign-in, and sign-out state changes:const { data: { subscription } } = client.auth.onAuthStateChange((event) => { console.log(event); }); // Call subscription.unsubscribe() when your UI no longer needs this listener.
Note: stopAutoRefresh() and dispose() do not cancel authentication initialization or token refresh already in progress. When that work finishes, it can schedule another refresh timeout. Account for this behavior when cleaning up your application.
Retrieve the current session as follows:
const { data: { session } } = await client.auth.getSession();
Refresh the current credentials and return the resulting session:
const { data } = await client.auth.refreshSession();
Restore a session from access and refresh tokens:
await client.auth.setSession({ access_token, refresh_token });
Use MFA Through the Relational Client
Multi-factor authentication (MFA) APIs are available through client.auth.mfa. They return { data, error }. Keep access tokens, refresh tokens, and MFA session tokens out of application logs.
Before making MFA calls, complete Setting Up Multi-Factor Authentication and initialize App Trust on client.app. For example, if your application uses reCAPTCHA v3:
import { ReCaptchaV3Provider } from "@fusabase/fusabase-relational";
client.appTrust.initialize({
provider: new ReCaptchaV3Provider("SITE_KEY")
});
await client.appTrust.getToken();
Replace SITE_KEY with the site key for the provider configured for your application.
For a pending MFA sign-in, signInWithPassword() returns error.code === "mfa_required" and error.mfa. Use the server-issued challenge and selected factor to complete sign-in:
async function signInWithRelationalMfa(
email, password, chooseFactor, readCode
) {
const result = await client.auth.signInWithPassword({ email, password });
if (!result.error) return result.data.session;
if (result.error.code !== "mfa_required" || !result.error.mfa) {
throw result.error;
}
const pending = result.error.mfa;
const selected = await chooseFactor(pending.factors);
const factor = pending.factors.find(item => item.id === selected?.id);
if (!factor) throw new Error("Select an available MFA factor.");
const challenge = {
factorId: factor.id,
challengeId: pending.challengeId,
mfaSessionToken: pending.mfaSessionToken
};
if (factor.factor_type === "phone") {
const sent = await client.auth.mfa.sendSignInSmsChallenge(challenge);
if (sent.error) throw sent.error;
} else if (factor.factor_type !== "totp") {
throw new Error("Unsupported MFA factor.");
}
const verified = await client.auth.mfa.challengeAndVerify({
...challenge,
code: await readCode(factor)
});
if (verified.error) throw verified.error;
return verified.data;
}
Supply two asynchronous UI callbacks:
chooseFactor: returns one factor from the supplied list.readCode: returns the code entered by the user as a string.
Both callbacks must reject their promises if the user cancels. signInWithRelationalMfa() resolves to the relational session after successful sign-in. Handle rejected promises in the calling code.
Keep pending MFA values private and discard them after completion, cancellation, or expiry.
For enrollment, sign in and verify the user’s email first. The following operations manage factors for the signed-in user.
Use enroll(params) to start time-based one-time password (TOTP) or phone-factor enrollment:
const { data } = await client.auth.mfa.enroll({ factorType: "totp" });
Use challenge(params) to create a challenge for an enrolled or pending factor:
const { data } = await client.auth.mfa.challenge({ factorId: "factor-id" });
Use verify(params) with the factor and challenge IDs returned by the preceding operations. code is the string entered by the user:
await client.auth.mfa.verify({ factorId, challengeId, code });
Use challengeAndVerify(params) to create and verify a challenge in one call:
await client.auth.mfa.challengeAndVerify({ factorId, code });
Use sendSignInSmsChallenge(params) to send an SMS challenge during MFA sign-in:
await client.auth.mfa.sendSignInSmsChallenge({
factorId, challengeId, mfaSessionToken
});
Use unenroll(params) to remove an enrolled factor:
await client.auth.mfa.unenroll({ factorId: "factor-id" });
Use listFactors() to list all, TOTP, and phone factors:
const { data } = await client.auth.mfa.listFactors();
Use getAuthenticatorAssuranceLevel(jwt?) to return current and next authentication assurance levels:
const { data } = await client.auth.mfa.getAuthenticatorAssuranceLevel();
TOTP Enrollment Example
The following example starts TOTP enrollment and creates its verification challenge. Render the returned provisioning value locally. When the user enters a code, call finishRelationalTotpEnrollment(code) with that string and handle any rejection.
const enrollment = await client.auth.mfa.enroll({ factorType: "totp" });
if (enrollment.error) throw enrollment.error;
// Render enrollment.data.totp.qr_code locally in your application UI.
const challenge = await client.auth.mfa.challenge({
factorId: enrollment.data.id
});
if (challenge.error) throw challenge.error;
async function finishRelationalTotpEnrollment(code) {
const verified = await client.auth.mfa.verify({
factorId: enrollment.data.id,
challengeId: challenge.data.id,
code
});
if (verified.error) throw verified.error;
return verified.data;
}
Hide the provisioning value and discard your application’s pending enrollment state after completion, cancellation, or expiry.
Use MFA with the JavaScript SDK
Use client.auth.mfa to enroll factors, complete sign-in challenges, and manage factors for the signed-in user. SDK operations return { data, error }. The example helpers check error and reject on failure; handle those rejections in your application UI.
Prerequisites and Initialization
- Complete the BASIC or IDCS requirements in Setting Up Multi-Factor Authentication.
- Reuse the
clientcreated in Getting Started. - Initialize App Trust once as shown in Use MFA Through the Relational Client. Reuse that initialization for the following examples.
Wait for authentication state and obtain an App Trust token:
const { error: authError } = await client.auth.initialize();
if (authError) throw authError;
await client.appTrust.getToken();
Before enrollment, reload the user and check email verification:
async function enrollmentUser() {
const { data, error } = await client.auth.getUser();
if (error) throw error;
const user = data.user;
if (!user) throw new Error("Sign in first.");
if (user.user_metadata.email_verified !== true) {
throw new Error("Verify your email first.");
}
return user;
}
Client Validation Requirements
Verified email: Require email verification in your enrollment flow.
- IDCS checks
email_verifiedat enrollment start and verification. A false or missing value returns an HTTP403 Forbiddenstatus code. - Refresh the user’s profile after email verification, as shown by
enrollmentUser().
User and session ownership: Enrollment requires a valid bearer token and an MFA session for the same user and project.
- Let the SDK manage enrollment session identifiers and tokens.
- Keep the factor ID returned by
enroll()and the challenge ID returned bychallenge(). - For incomplete sign-in, use the challenge and factor values in
error.mfa, as shown bysignInWithRelationalMfa().
Factor selection: Offer enabled TOTP or SMS methods.
- Select a sign-in factor from
error.mfa.factorsand preserve itsid. - Complete enrollment with the factor and challenge returned for that enrollment attempt.
Inputs: Send one-time passwords (OTPs) as strings to preserve leading zeros.
- BASIC expects six digits. TOTP codes refresh every 30 seconds.
- BASIC SMS country codes use
+followed by one to three digits. - The combined country code and phone number must contain at most 15 digits, without spaces or punctuation.
- IDCS also validates enrollment inputs.
Enroll an Authenticator App
- Call
enrollmentUser()to check the signed-in user’s verification status. - Start enrollment with
client.auth.mfa.enroll({ factorType: "totp" }). - Display the manual key from
data.totp.secretor renderdata.totp.qr_codelocally. The provisioning value can be anotpauth://URI rather than an image URL. - Create a challenge and verify the code entered by the user, following TOTP Enrollment Example.
Keep the provisioning secret only for pending enrollment. Do not log it or send it to an external QR-code service. Hide it and discard your application’s pending state after completion, cancellation, or expiry.
Enroll an SMS Factor
Pass countryCode separately from the national phone number. Phone enrollment requests an SMS; challenge() then returns the challenge needed to verify that pending enrollment.
async function beginSmsEnrollment(countryCode, phoneNumber) {
const user = await enrollmentUser();
const enrollment = await client.auth.mfa.enroll({
factorType: "phone",
countryCode,
phone: phoneNumber
});
if (enrollment.error) throw enrollment.error;
const challenge = await client.auth.mfa.challenge({
factorId: enrollment.data.id
});
if (challenge.error) throw challenge.error;
return async function finishSmsEnrollment(code) {
if (typeof code !== "string" || code.length === 0) {
throw new Error("Enter the SMS code as a string.");
}
const { data, error } = await client.auth.getSession();
if (error) throw error;
if (data.session?.user.id !== user.id) {
throw new Error("Sign in again and restart SMS enrollment.");
}
const verified = await client.auth.mfa.verify({
factorId: enrollment.data.id,
challengeId: challenge.data.id,
code
});
if (verified.error) throw verified.error;
return verified.data;
};
}
Call beginSmsEnrollment(countryCode, phoneNumber) when the user requests enrollment. It returns a completion function; call that function with the entered code string and handle rejection. Allow only one verification submission at a time.
After a wrong code, the relational SDK retains the challenge context. The user can submit another code through the same completion function while the backend permits further attempts. Restart after expiry or challenge invalidation.
For other errors, reload the factor list before repeating enrollment: the server might have completed enrollment even if the SDK could not return the session. To request another SMS, start a fresh enrollment attempt after the permitted cooldown and keep its returned completion function. Do not send another SMS automatically.
Complete a Sign-In Challenge
Use signInWithRelationalMfa() from your sign-in UI. Supply the email, password, factor-selection callback, and code-entry callback:
const session = await signInWithRelationalMfa(
email, password, chooseFactor, readCode
);
The helper handles error.mfa, requests an SMS when the selected factor requires one, and completes the challenge. It resolves to the relational session after successful sign-in. The callbacks must reject if the user cancels; handle rejection before updating your UI to show a signed-in state.
Session Expiry and Rate Limits
| Limit | BASIC | IDCS |
|---|---|---|
| Enrollment session | 10 minutes from creation | 5 minutes from creation |
| Sign-in continuation session | 10 minutes from creation | 5 minutes from creation; IDCS state can expire sooner |
| SMS code validity | Up to 10 minutes, bounded by the parent session | Controlled by IDCS |
| Failed code checks | Five evaluated failures per challenge; the fifth invalidates it | Controlled by IDCS |
| SMS sends | Three successful sends per challenge, including resends | Controlled by IDCS |
| SMS resend cooldown | 30 seconds | Controlled by IDCS |
Session handling: Continuing enrollment or resending a code does not extend the parent session deadline.
- Use the latest SMS code and enrollment response after a resend.
- Restart the flow after expiry or challenge invalidation.
- Discard session values after successful completion.
Additional BASIC project quotas: SMS enrollment and sign-in have separate configurable per-email daily quotas.
- Code checks use the project’s
verifyoperation quota. - These quotas apply in addition to fixed challenge caps. Values depend on the project configuration.
Delete Factors and Recover Accounts
Client factor management: Use client.auth.mfa to list and remove factors for the signed-in user.
async function listFactors() {
const { data, error } = await client.auth.mfa.listFactors();
if (error) throw error;
return data.all;
}
async function removeFactor(selectedId) {
const factors = await listFactors();
const selected = factors.find(factor => factor.id === selectedId);
if (!selected) throw new Error("Factor is no longer enrolled.");
const { error } = await client.auth.mfa.unenroll({
factorId: selected.id
});
if (error) throw error;
return await listFactors();
}
Refresh the factor list after deletion. Removing all factors leaves the user without an enrolled second factor. Handle failures and signed-in user changes in the calling UI.
Administrator recovery: Project owners can reset all factors through the Console’s user management.
- Console API paths are relative to
/_/baas-panel/and require owner authorization. - To reset BASIC factors, use
POST /onprem/{project_id}/mfa/users/{user_guid}/factors/reset. - To reset IDCS factors, use
POST /idcs/{project_id}/mfa/users/factors/resetwith{"userGuid":"<IDCS user ID>"}. Use the IDCS SCIM user ID, not the BaaS UUID. - To delete an individual BASIC factor, use
DELETE /idm/{project_id}/user/factors/{factor_id}?uid=<user-id>. - Verify the user’s identity before an administrative reset.
- Have the user enroll again afterward.
- Keep administrator credentials out of client applications.
Handle Errors and Protect Credentials
Incomplete sign-in: Handle error.code === "mfa_required" and use the pending challenge in error.mfa.
- Present
error.mfa.factorsfor selection. - Complete sign-in with the server-issued challenge and session values, as shown by
signInWithRelationalMfa(). - Treat sign-in as complete only after the helper returns a session.
Invalid requests: For an HTTP 400 Bad Request status code, supply missing fields or use matching factors.
- For HTTP
401 Unauthorizedor403 Forbidden, check for invalid user or session tokens, missing App Check, an unverified IDCS email, or factors that are not enabled.
Exhausted attempts: BASIC challenge caps return an HTTP 401 Unauthorized status code with MFA verification attempt limit exceeded or SMS request limit exceeded.
- BASIC resend cooldown and IDCS throttling return an HTTP
429 Too Many Requestsstatus code. - Stop automatic retries, and show the appropriate retry or restart action.
- Do not treat every HTTP
401 Unauthorizedresponse as a request to refresh the user token.
Sensitive values: Never log OTPs, shared secrets, bearer tokens, or MFA session tokens.
- Keep provider credentials in server configuration.
- Keep authenticator device clocks synchronized.