Docs
Contents

Authentication (All Login Methods)

Overview and use cases

The user authentication surface for app projects: Email/Password, OAuth 2.0 (including the configuration-based Custom OAuth2 introduced in 2.6.0), Magic URL, Phone, anonymous, JWT, Custom Token, plus MFA multi-factor protection. How to choose:

This page describes app project user authentication. Console management-plane login (account-password Session / OAuth Browser Session → short-term JWT) is a control-plane credential; see console-sdk/nodejs.md and organization.md. Providers and user boundaries of the two must not be mixed.

Prerequisites

Usage workflow

Email/Password (built-in)

  1. Register: account.create({ userId: ID.unique(), email, password, name }) (name optional).

  2. Log in: account.createEmailPasswordSession({ email, password }); the SDK manages the Session Cookie automatically.

  3. Current user: account.get(); log out: account.deleteSession('current').

OAuth 2.0 (social / enterprise Providers)

  1. In Console → Auth → Providers, enable the target Provider and enter credentials; add the callback URL to the upstream app configuration: {endpoint}/account/sessions/oauth2/callback/{provider}/{projectId} ({provider} lowercase).

  2. Front-end redirect: account.createOAuth2Session({ provider, success, failure }); success/failure must be paths under a registered Platform origin.

  3. Common enums: OAuthProvider.Github, Google, Apple, Facebook, Discord, Microsoft, Gitlab, Linkedin, Okta, Auth0, Authentik, Salesforce, Oidc, etc.; internal unified authentication uses the existing OAuthProvider.Weavefox. Do not cast strings.

Custom OAuth2 (2.6.0 highlight)

Suited for enterprise identity systems whose upstream provides standard OAuth 2.0 Authorization Code; configurable directly in the project without adding a server-side Provider class:

  1. In Console, save the configuration in the project's OAuth Provider management entry: Client ID/Secret, Authorization/Token/UserInfo endpoints, clientAuthMethod, field mappings; on the login side use OAuthProvider.CustomOauth2 (both agentbase-web-sdk@2.12.0 and agentbase-node-sdk@2.12.0 already include it; do not concatenate customOauth2 from strings).

  2. First verify the Providers enabled for the current project in Console "Authentication → Settings → Test OAuth2 Login", then integrate app login; test Sessions and Console Sessions are mutually isolated.

  3. Configuration boundaries:

    • The three endpoints (plus an optional email endpoint since 2.7.0; leave empty to disable) must be absolute public HTTPS addresses and must not point to localhost, private networks, cloud metadata, or contain userinfo/fragment; Token/UserInfo redirects only allow a limited number of same-origin HTTPS hops.

    • clientAuthMethod only allows client_secret_post or client_secret_basic.

    • subjectPath and emailPath are required; field paths only support dot-separated object properties (plus decimal array indices since 2.7.0, e.g. 0.email); expressions are not executed; emailVerifiedPath only marks the email as verified if it explicitly returns boolean true.

    • Client Secret is not echoed after saving; leaving it empty keeps the original value; changing Client ID, endpoints (including the email endpoint added in 2.7.0), or subjectPath switches identity generation and will not silently take over old Identities.

    • OIDC Discovery, PKCE, dynamic Client Registration, and custom grants are not supported; cannot be enabled if the dedicated callback origin is missing or fails HTTPS isolation rules.

  4. 2.7.0 additions (appbase release-2.7.0 PR 565 etc.):

    • Gitee integration built in: the Console configuration form directly shows Gitee example hints (subject id, email 0.email, name name, verification status left empty), and adds an optional "email endpoint" field (e.g. Gitee https://gitee.com/api/v5/emails); after configuring a dedicated email endpoint, both the email and its verification status are read from the same response of that endpoint. No new SDK enum was added: agentbase-web-sdk@2.12.0 and agentbase-node-sdk@2.12.0 in OAuthProvider have no Gitee; Gitee still goes through OAuthProvider.CustomOauth2.

    • Login test custom Scope: the Custom OAuth2 card in Console "Test OAuth2 Login" offers an optional Scope input (comma- or whitespace-separated; trimmed before submission, empty values filtered, deduplicated; empty input does not send scopes); the Scope is only passed to Custom OAuth2 — other Providers never receive this parameter even if it was typed on the page; switching region/project clears the input and rebinds the public test Client. Test Sessions and Console Sessions remain mutually isolated.

    • State and email mismatch blocking: the login state is single-use and bound to project, browser, callback, Client ID, and server-side state revision; any change to Client Secret, any endpoint, clientAuthMethod, or any field mapping rotates the state revision — even if configuration goes from A to B and back to A, old states do not become valid again. When the upstream returns an integer subject (e.g. Gitee's numeric id), the server normalizes it to a string.

Magic URL / Phone OTP (passwordless)

  1. Send: account.createMagicURLToken({ userId, email, url }) (url optional) (or account.createEmailToken / account.createPhoneToken to trigger OTP).

  2. On the callback page take userId + secret: account.createSession({ userId, secret }); Phone uses account.updatePhoneSession.

Anonymous (guest)

  1. account.createAnonymousSession(); anonymous users get a unique userId with email/phone set to null.

  2. Convert to a formal account: account.updateEmail({ email, password }) (anonymous users have no old password, so this password becomes the newly set password; userId unchanged, all data preserved, email verification state reset), or while the anonymous Session is active directly call createOAuth2Session to merge into the same account automatically.

  3. Rate limit is about 50 requests per IP per hour; for the full guide see skills/ob-agentbase/references/anonymous-auth.md.

JWT (server-side on behalf of user)

After the user logs in, call account.createJWT({ duration }) (duration optional) (default 15 minutes) to obtain jwt and hand it to a trusted backend; the backend uses agentbase-node-sdk's Client().setJWT(...) to call as that user, with permissions consistent with the issuer. Do not print or persist JWTs.

Custom Token (your own account system)

  1. The business backend completes external identity verification itself (SSO gateway, risk control, multi-step authentication, etc.).

  2. The backend issues a short-term token with the Server SDK: users.createToken({ userId }) → returns a one-time secret (see users.md).

  3. The front end exchanges account.createSession({ userId, secret }) for a formal Session. This route does not depend on OAuth redirects or upstream UserInfo contracts.

MFA (multi-factor)

  1. Account-level switch: account.updateMFA({ mfa: true }).

  2. Register an authenticator: account.createMFAAuthenticator({ authenticatorType }) (TOTP), verify activation with account.updateMFAAuthenticator; account.listMFAFactors lists registered factors.

  3. If login hits MFA: account.createMFAChallenge({ factorId }) → account.updateMFAChallenge({ challengeId, otp }) to complete the second verification before getting a usable Session.

  4. Recovery codes: account.createMFARecoveryCodes / getMFARecoveryCodes / updateMFARecoveryCodes; use recovery codes as a fallback when switching devices.

  5. Accounts with MFA enabled must complete the corresponding factor challenge when logging in via automation scripts to obtain usable credentials.

Key parameters and returns

CallKey parametersReturns
createuserId (ID.unique() or custom), email, password, name (optional)Models.User
createEmailPasswordSessionemail, passwordSession (secret in Cookie, not in plaintext response body)
createOAuth2Sessionprovider enum, success, failureBrowser redirect completes login, no response body
createSession (token-to-session)userId, secretSession
createJWTduration (optional; seconds, default 900){ jwt }
createMagicURLTokenuserId, email, url (optional)Token (includes userId)
updateMFA / MFA familymfa, authenticatorType, factorId, challengeId, otpUser / MfaType / Challenge etc.

Errors and boundaries

SDK Category Differences

Examples by language

The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).

Email/Password Registration and Sign-in

The Node Server SDK does not initiate user sign-in (see "SDK Category Differences"); sign-in initiation is unified on the client Session side; Node's role is described in the "JWT and Custom Token" card.

import { Client, Account, ID } from 'agentbase-web-sdk';

const client = new Client()
    .setEndpoint(import.meta.env.VITE_APPWRITE_ENDPOINT)   // Includes /v1
    .setProject(import.meta.env.VITE_APPWRITE_PROJECT_ID);
const account = new Account(client);

await account.create({ userId: ID.unique(), email, password, name });  // Register once only
await account.createEmailPasswordSession({ email, password });         // Session is stored in a Cookie
const me = await account.get();            // Throws 401 = not logged in / session expired
await account.deleteSession('current');    // Log out the current device

OAuth 2.0 Social / Enterprise Sign-in

Sign-in is completed via browser redirect: there is no REST form; server-side languages do not initiate the redirect, so this card is client-only.

// Prerequisites: the Provider is enabled in the Console and the callback URL has been registered in the upstream app configuration (see Usage workflow)
await account.createOAuth2Session({
    provider: OAuthProvider.Github,   // Enum; do not force-cast from strings
    success: window.location.origin + '/',
    failure: window.location.origin + '/?error=auth_failed'
});

Custom OAuth2 (Enterprise Identity Systems)

First save the Provider configuration in the Console (Client ID/Secret, the three endpoints, clientAuthMethod, and field mappings) and verify it using "Test OAuth2 Login", then integrate it into your application's login; login initiation uses the same browser redirect as OAuth2, with no REST form.

await account.createOAuth2Session({
    provider: OAuthProvider.CustomOauth2,   // 2.6.0 built-in enum; do not string-concatenate customOauth2
    success: window.location.origin + '/',
    failure: window.location.origin + '/?error=auth_failed'
});

Magic URL / Phone OTP (passwordless)

After sending the token email/SMS, the callback page exchanges userId + secret for a formal Session; the token sending endpoint is not listed in the API reference, so REST is omitted.

// 1. Send the login email (optional custom redirect URL); for Phone SMS OTP use createEmailToken / createPhoneToken
await account.createMagicURLToken({
    userId: ID.unique(),
    email: 'user@example.com',
    url: window.location.origin + '/auth/magic'
});
// 2. On the callback page, exchange userId + secret for a formal Session; Phone corresponds to updatePhoneSession
await account.createSession({ userId, secret });

Anonymous (guest)

Anonymous Sessions have a unique userId with null email/phone; rate limiting is approximately 50 per IP per hour. Conversion to a permanent account goes through updateEmail (or createOAuth2Session automatically merges when the anonymous Session is active); the userId is unchanged and all data is preserved.

await account.createAnonymousSession();
// Promotion: anonymous users have no old password, so this password becomes the newly set password; email verification status reset
await account.updateEmail({ email: 'user@example.com', password: '<password>' });

JWT and Custom Token (Server-side Credentials)

The server verifies the external identity itself and issues a Custom Token for the frontend to exchange for a Session (no dependence on OAuth redirects or upstream UserInfo contracts); or a signed-in user's outbound JWT is given to a trusted backend to perform calls on their behalf.

import { Client, Users } from 'agentbase-node-sdk';

// Custom Token: backend verifies the external identity itself, then issues a short-lived token; secret is handed to the frontend to exchange for a Session
const token = await new Users(client).createToken('<userId>');   // { secret, expire }

// JWT on-behalf call: load the client with the user JWT; permissions match the issuer; do not print or persist the JWT
const userClient = new Client()
    .setEndpoint(process.env.APPBASE_ENDPOINT!)
    .setProject(process.env.APPBASE_PROJECT_ID!)
    .setJWT('<jwt>');

MFA (multi-factor)

Account-level toggle → register authenticator → second-factor verification at sign-in → recovery code fallback; all are user Session operations, REST endpoints are not listed in the API reference, so REST is omitted.

await account.updateMFA({ mfa: true });   // Account-level switch
// Register TOTP authenticator and verify activation
await account.createMFAAuthenticator({ authenticatorType: 'totp' });
await account.updateMFAAuthenticator({ authenticatorType: 'totp', otp: '<code>' });
await account.listMFAFactors();           // Registered factors

// MFA hit on login: createMFAChallenge first; a Session is only available after second-factor verification passes
await account.createMFAChallenge({ factorId: '<factorId>' });
await account.updateMFAChallenge({ challengeId: '<challengeId>', otp: '<code>' });

// Recovery codes: generate / view / regenerate (fallback when switching devices)
await account.createMFARecoveryCodes();
await account.getMFARecoveryCodes();
await account.updateMFARecoveryCodes();

Example Guide