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:
Standard web / mobile apps: base on Email/Password and layer on social OAuth as needed.
Enterprise identity systems: standard Authorization Code upstream via Custom OAuth2 (built in since 2.6.0, no server-side Provider class needed); if you already have your own identity verification backend, use Custom Token.
Passwordless / low-friction: Magic URL, anonymous (can later be converted losslessly).
Server-side calls on behalf of the user: JWT; server-side orchestration of external identity: Custom Token.
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
The project exists and client origins are registered (browsers require a Web Platform, see overview.md).
Enable each method via Console → Auth → Settings / Providers; anonymous login is enabled by default on new projects — turn it off if unused.
Magic URL / Email verification / recovery emails require SMTP configured on the instance.
Custom OAuth2 requires the upstream to provide standard Authorization Code: Client ID/Secret, the Authorization/Token/UserInfo endpoints, and field mappings.
Usage workflow
Email/Password (built-in)
Register:
account.create({ userId: ID.unique(), email, password, name })(nameoptional).Log in:
account.createEmailPasswordSession({ email, password }); the SDK manages the Session Cookie automatically.Current user:
account.get(); log out:account.deleteSession('current').
OAuth 2.0 (social / enterprise Providers)
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).Front-end redirect:
account.createOAuth2Session({ provider, success, failure });success/failuremust be paths under a registered Platform origin.Common enums:
OAuthProvider.Github,Google,Apple,Facebook,Discord,Microsoft,Gitlab,Linkedin,Okta,Auth0,Authentik,Salesforce,Oidc, etc.; internal unified authentication uses the existingOAuthProvider.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:
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 useOAuthProvider.CustomOauth2(bothagentbase-web-sdk@2.12.0andagentbase-node-sdk@2.12.0already include it; do not concatenatecustomOauth2from strings).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.
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.
clientAuthMethodonly allowsclient_secret_postorclient_secret_basic.subjectPathandemailPathare 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;emailVerifiedPathonly marks the email as verified if it explicitly returns booleantrue.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
subjectPathswitches 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.
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, email0.email, namename, verification status left empty), and adds an optional "email endpoint" field (e.g. Giteehttps://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.0andagentbase-node-sdk@2.12.0inOAuthProviderhave noGitee; Gitee still goes throughOAuthProvider.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 numericid), the server normalizes it to a string.
Magic URL / Phone OTP (passwordless)
Send:
account.createMagicURLToken({ userId, email, url })(urloptional) (oraccount.createEmailToken/account.createPhoneTokento trigger OTP).On the callback page take
userId+secret:account.createSession({ userId, secret }); Phone usesaccount.updatePhoneSession.
Anonymous (guest)
account.createAnonymousSession(); anonymous users get a unique userId withemail/phoneset tonull.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 callcreateOAuth2Sessionto merge into the same account automatically.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)
The business backend completes external identity verification itself (SSO gateway, risk control, multi-step authentication, etc.).
The backend issues a short-term token with the Server SDK:
users.createToken({ userId })→ returns a one-timesecret(see users.md).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)
Account-level switch:
account.updateMFA({ mfa: true }).Register an authenticator:
account.createMFAAuthenticator({ authenticatorType })(TOTP), verify activation withaccount.updateMFAAuthenticator;account.listMFAFactorslists registered factors.If login hits MFA:
account.createMFAChallenge({ factorId })→account.updateMFAChallenge({ challengeId, otp })to complete the second verification before getting a usable Session.Recovery codes:
account.createMFARecoveryCodes/getMFARecoveryCodes/updateMFARecoveryCodes; use recovery codes as a fallback when switching devices.Accounts with MFA enabled must complete the corresponding factor challenge when logging in via automation scripts to obtain usable credentials.
Key parameters and returns
| Call | Key parameters | Returns |
|---|---|---|
create | userId (ID.unique() or custom), email, password, name (optional) | Models.User |
createEmailPasswordSession | email, password | Session (secret in Cookie, not in plaintext response body) |
createOAuth2Session | provider enum, success, failure | Browser redirect completes login, no response body |
createSession (token-to-session) | userId, secret | Session |
createJWT | duration (optional; seconds, default 900) | { jwt } |
createMagicURLToken | userId, email, url (optional) | Token (includes userId) |
updateMFA / MFA family | mfa, authenticatorType, factorId, challengeId, otp | User / MfaType / Challenge etc. |
Errors and boundaries
Users of all methods share the same project user system; one account can bind multiple login methods at the same time.
Common OAuth failures: Provider not enabled, callback URL not registered as a Platform,
successdomain not registered — for all three, first check platform registration in overview.md.For Custom OAuth2, upstream URLs violating HTTPS/SSRF rules or missing field mappings (
subjectPath/emailPath) cause direct configuration failure or login failure; compare failures against the Console login test first.Sessions have a relatively long default validity period (adjustable in Console → Auth); after expiry,
account.get()throws 401; the frontend treats this as not signed in.Credentials (passwords,
secret,jwt, Sessions) must never be written into source code, command arguments, logs, or version control.
SDK Category Differences
Web / Client SDK (client-sdk/web.md): the initiating end for all sign-in methods; OAuth uses browser redirects; Sessions are restored via three layers: Cookie / header / fallback.
Server SDK: does not initiate user sign-in; only performs Custom Token issuance (
users.createToken), user management, and controlled impersonation calls with JWT / Session.Console SDK: management-plane credentials (Console account Session,
setCookie, short-lived JWT), which are a separate boundary from application user authentication.Java / other languages use the same isomorphic method names; see integration and the corresponding index.
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.
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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 deviceimport io.agentbase.ID;
import io.agentbase.services.Account;
Account account = new Account(client); // For client initialization, see server-sdk/java.md
account.create(ID.unique(), "user@example.com", "<password>", "Example User"); // Register once only
account.createEmailPasswordSession("user@example.com", "<password>"); // Session is stored in a Cookie
Object me = account.get(); // Throws 401 = not logged in / session expired
account.deleteSession("current"); // Log out the current devicefrom agentbase.id import ID
from agentbase.services.account import Account # account module under agentbase.services
account = Account(client) # client initialization see server-sdk/python.md
account.create(user_id=ID.unique(), email='user@example.com', password='<password>', name='Example User') # Register once only
account.create_email_password_session(email='user@example.com', password='<password>') # Session is stored in a Cookie
me = account.get() # Throws 401 = not logged in / session expired
account.delete_session('current') # Log out the current deviceaccount := agentbase.NewAccount(cl) // facade constructor; cl is a Client already loaded with a project Key
_, _ = account.Create(id.Unique(), "user@example.com", "<password>",
account.WithCreateName("Example User")) // Register only once; pass userId/email/password positionally, name via WithCreateName
_, _ = account.CreateEmailPasswordSession("user@example.com", "<password>") // Session is delivered via Set-Cookie; after retrieving the cookie, setSession can replay it
me, err := account.Get() // Throws 401 = not logged in / session expired
_, _ = account.DeleteSession("current") // Log out the current device# $APPBASE_ENDPOINT contains /v1. Login: the Session is delivered via Set-Cookie; use -c to persist it for subsequent replay
curl -sS -c cookies.txt -X POST "$APPBASE_ENDPOINT/account/sessions/email" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-d '{"email":"user@example.com","password":"<password>"}'
# Current user: GET /account (replays Cookie); log out current device: DELETE /account/sessions/current
curl -sS -b cookies.txt "$APPBASE_ENDPOINT/account" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "Authorization: Bearer $APPBASE_API_KEY"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.
- Web (user session)
// 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.
- Web (user session)
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.
- Web (user session)
- Java
- Python
- Go
// 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 });import io.agentbase.ID;
// 1. Send the login email (optional custom redirect URL); for Phone SMS OTP use createEmailToken / createPhoneToken
account.createMagicURLToken(ID.unique(), "user@example.com", "https://app.example.com/auth/magic", null);
// 2. On the callback page, exchange userId + secret for a formal Session; Phone corresponds to updatePhoneSession
account.createSession(userId, secret);from agentbase.id import ID
# 1. Send the login email (optional custom callback URL); Phone SMS OTP is triggered via create_email_token / create_phone_token
account.create_magic_url_token(user_id=ID.unique(), email='user@example.com',
url='https://app.example.com/auth/magic')
# 2. On the callback page, exchange userId + secret for a full Session; Phone maps to update_phone_session
account.create_session(user_id=user_id, secret=secret)account := agentbase.NewAccount(cl) // facade constructor; cl is a Client already loaded with a project Key
// 1. Send the login email (optional custom redirect URL); for Phone SMS OTP use CreateEmailToken / CreatePhoneToken
_, _ = account.CreateMagicURLToken(id.Unique(), "user@example.com",
account.WithCreateMagicURLTokenUrl("https://app.example.com/auth/magic"))
// 2. On the callback page, exchange userId + secret for a formal Session; Phone corresponds to UpdatePhoneSession
_, _ = 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.
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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>' });account.createAnonymousSession();
account.updateEmail("user@example.com", "<password>"); // Promotion: anonymous users have no old password, so this password becomes the newly set passwordaccount.create_anonymous_session()
account.update_email(email='user@example.com', password='<password>')_, _ = account.CreateAnonymousSession() // Anonymous Session: unique userId, with email/phone null
// Promotion: anonymous users have no old password, so this password becomes the newly set password; userId unchanged, email verification status reset
_, _ = account.UpdateEmail("user@example.com",
account.WithUpdateEmailPassword("<password>"))# Anonymous login (no request body): Session is delivered via Set-Cookie
curl -sS -c cookies.txt -X POST "$APPBASE_ENDPOINT/account/sessions/anonymous" \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID"
# Upgrade: PATCH /account/email (body: email, password)
curl -sS -b cookies.txt -X PATCH "$APPBASE_ENDPOINT/account/email" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-d '{"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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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>');// Outbound JWT for logged-in users: delegate calls to a trusted backend (default 15 minutes)
const { jwt } = await account.createJWT();
// Client-side wrap-up of the Custom Token flow: exchange token for Session
await account.createSession({ userId: '<userId>', secret: token.secret });import io.agentbase.services.Users;
var token = new Users(client).createToken("<userId>", null, null); // { secret, expire }
// Use the Client SDK in the browser: account.createSession({ userId, secret: token.secret })from agentbase.services.users import Users
token = Users(client).create_token('<userId>') # Method names mirror the structure (snake_case); returns { secret, expire }token, err := agentbase.NewUsers(cl).CreateToken("<userId>") // Isomorphic to the Node side; Length / Expire via WithCreateTokenLength / WithCreateTokenExpire, returns { secret, expire }# Server-side issuance of short-lived Custom Tokens (optional body parameters, see the users page in the API reference)
curl -sS -X POST "$APPBASE_ENDPOINT/users/<userId>/tokens" \
-H 'Content-Type: application/json' \
-H "X-Appwrite-Project: $APPBASE_PROJECT_ID" \
-H "Authorization: Bearer $APPBASE_API_KEY" \
-d '{}'
# Issue a JWT for an existing Session: POST /users/<userId>/jwts; user-state outbound JWT: POST /account/jwts (replays the Session Cookie)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.
- Web (user session)
- Java
- Python
- Go
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();import io.agentbase.enums.AuthenticationFactor;
import io.agentbase.enums.AuthenticatorType;
account.updateMFA(true); // Account-level switch
account.createMFAAuthenticator(AuthenticatorType.TOTP); // Register TOTP authenticator (AuthenticatorType enum)
account.updateMFAAuthenticator(AuthenticatorType.TOTP, "<code>"); // Validate activation
account.listMFAFactors(); // Registered factors
// Login hits MFA: first createMFAChallenge (use the AuthenticationFactor enum for factor); a usable Session is available only after the second-factor verification passes
account.createMFAChallenge(AuthenticationFactor.TOTP);
account.updateMFAChallenge("<challengeId>", "<code>");
// Recovery codes: generate / view / regenerate (fallback when switching devices)
account.createMFARecoveryCodes();
account.getMFARecoveryCodes();
account.updateMFARecoveryCodes();from agentbase.enums.authentication_factor import AuthenticationFactor
from agentbase.enums.authenticator_type import AuthenticatorType
account.update_mfa(mfa=True) # Account-level switch
account.create_mfa_authenticator(type=AuthenticatorType.TOTP) # Register a TOTP authenticator (parameter name type)
account.update_mfa_authenticator(type=AuthenticatorType.TOTP, otp='<code>') # Validate activation
account.list_mfa_factors() # Registered factors
# Login hits MFA: call create_mfa_challenge first (factor uses the AuthenticationFactor enum); a usable Session is only available after second-factor verification passes
account.create_mfa_challenge(factor=AuthenticationFactor.TOTP)
account.update_mfa_challenge(challenge_id='<challengeId>', otp='<code>')
# Recovery codes: generate / view / regenerate (fallback when switching devices)
account.create_mfa_recovery_codes()
account.get_mfa_recovery_codes()
account.update_mfa_recovery_codes()_, _ = account.UpdateMFA(true) // Account-level switch
_, _ = account.CreateMFAAuthenticator("totp") // Register TOTP authenticator
_, _ = account.UpdateMFAAuthenticator("totp", "<code>") // Validate activation
_, _ = account.ListMFAFactors() // Registered factors
// Login hits MFA: first CreateMFAChallenge (pass the enum string value for factor); a usable Session is available only after the second-factor verification passes
_, _ = account.CreateMFAChallenge("totp")
_, _ = account.UpdateMFAChallenge("<challengeId>", "<code>")
// Recovery codes: generate / view / regenerate (fallback when switching devices)
_, _ = account.CreateMFARecoveryCodes()
_, _ = account.GetMFARecoveryCodes()
_, _ = account.UpdateMFARecoveryCodes()Example Guide
Complete call examples for each language are centralized in the language tree
examples/(organized by "SDK-axis initialization → feature-axis feature points").Runnable automation examples in this repo (sign-in, project creation, platform registration combos): main repo demo templates
assets/examples/team-kanban-demo/scripts/auto-setup.mjs(plain-text path reference, not in this tree).