Docs
Contents

Authentication Overview

Feature Overview

The Agentbase Authentication (Auth) service provides enterprise-grade, full-lifecycle account systems, diverse Identity Providers, multi-tenant Teams & RBAC Roles, fine-grained Permission Strings, and secure session management for End Users within a Project. When building enterprise-grade AI agents, knowledge platforms, and business applications (such as the example project 企业智能客服与知识中台, Project ID: enterprise-ai-hub-210), the Auth service not only handles registration, login, and multi-factor authentication (MFA) for Web and mobile users, but also serves as the core identity foundation for underlying data security (Databases row-level ACL, Storage file-level ACL, Memory per-user memory isolation, and Messaging target delivery).

In Agentbase's two-layer permission architecture, Project Auth (project end-user authentication) and Console Organization Auth (Console organization management authentication) are strictly physically isolated:


Core Concepts and Architecture

Agentbase Auth builds a complete identity security closed loop around “user identity lifecycle → authentication credential issuance → team and label mapping → resource ACL authorization evaluation”. The diagram below shows the full architecture chain for an end user from initiating authentication to accessing protected project resources:

Authentication Overview: workflow diagram, not a runtime screenshot

Flow diagram, not a runtime screenshot; read the relationships between steps or states along the arrows.

View the flow diagram in full size

Core Concepts

Core conceptIdentifier and format exampleTechnical definition and lifecycle description
Useruser_zhangwei_001, user_lina_002A unique natural person or business account entity within the project. Contains name (name), unique email (email), E.164-format phone number (phone), verification status (emailVerification / phoneVerification), account enabled/disabled status (status), preference key-values (prefs), and custom labels (labels).
SessionSession ID + HTTP CookieA persistent context created after the user logs in successfully via email/password, OTP, Magic URL, or OAuth2. Sessions are governed by the project-level Session length (validity period) and Sessions limit (maximum concurrent sessions per user), and support kicking out a single session or revoking all sessions.
User JWT (JSON Web Token)X-Appwrite-JWT: eyJhbG...A short-lived stateless token (fixed 15-minute validity) issued when a logged-in client calls account.createJWT(), dedicated to securely passing the current end-user identity from the frontend to an enterprise self-built backend service or SQL Proxy user-context endpoint, so the backend executes operations with that end user's permissions.
Server API KeyX-Appwrite-Key: <APPBASE_API_KEY>A project-level server-side management key bound to fine-grained functional permission domains (Scopes, such as users.read, users.write, teams.write, databases.write). Restricted to trusted backends only (e.g. agentbase-node-sdk@2.10.0); it must never be exposed in browser frontends.
Third-party identity (Identity)Identity ID + Provider UIDWhen a user signs in via public OAuth2 (such as GitHub, Google) or custom OAuth2 (Custom OAuth2, such as Gitee or enterprise SSO), the system creates an association record binding the external identity source's Subject UID, access token, and the in-project User.
User Labelsvip, architect, internalAlphanumeric attribute labels applied to users by administrators via the Console or Server SDK. Labels are automatically mapped to runtime permission roles label:<name> (e.g. Role.label('vip')), suitable for flat, cross-team hierarchical authorization.
Teams & Membershipsteam_support_ops, team_kb_governanceMulti-tenant organizational units within a project for end users. After joining a team, a user becomes a member (Membership) and can be assigned fully custom in-team roles (e.g. owner, admin, support_lead, auditor), enabling department-level or customer-tenant-level data sharing.
TargetsEmail / SMS / Push TargetNotification delivery endpoints associated with a user. When a user is created with an email or phone number, the corresponding Email / SMS Target is automatically generated for the Messaging service to deliver notifications, alerts, and support ticket status changes.

Roles, Entry Points, and Relationships

Console Entry and Routes

Organization Roles and API Key Scope Permission Matrix

When operating Auth resources in the Console or via the Server API, the permission boundaries of different organization member roles and API Key Scopes are as follows:

Operation domainResources and operations involvedRequired API Key ScopeOrganization roles allowed to executeRead-only or unauthorized roles
User readQuery user list, read user details, preferences, labels, sessions, and member listsusers.readowner, admin, developer, editor, analystbilling
User writeCreate users, modify email/phone/password/labels/preferences, ban/unban, revoke sessions, delete usersusers.writeowner, admin, developer, editorbilling, analyst
Team readQuery team lists, team details, and membership liststeams.readowner, admin, developer, editor, analystbilling
Team writeCreate/rename/delete teams, invite or add team members, modify member rolesteams.writeowner, admin, developer, editorbilling, analyst
Notification target managementCreate, update, or delete Email / SMS / Push targets for userstargets.read / targets.writeowner, admin, developer, editorbilling, analyst
Auth security policies and OAuth2 configurationModify Security policies, enable/disable login methods, configure Custom OAuth2Project-level management permission (Console state)owner, admin, developereditor, billing, analyst

Relationships with Other Product Modules

  1. Structured Databases: Table-level permissions and Row Security for database tables (e.g. customer_tickets under enterprise_biz_db) directly use role strings generated by Auth (e.g. user:user_zhangwei_001, team:team_support_ops/admin, label:vip) for access control.

  2. File Storage: Storage buckets kb_enterprise_docs and agent_multimedia_bucket use Bucket Permissions and File Security to identify the currently logged-in Auth user and decide whether to allow uploading, listing, or previewing files.

  3. Long-term Memory: The agent memory module uses the Auth user's User ID (e.g. user_zhangwei_001 and user_lina_002) as the primary key for memory ownership, extracting personalized profiles and long-term factual memory.

  4. Messaging: Targets (email, phone, device push tokens) registered automatically or manually for users in Auth directly serve as the target carriers for Messaging Topics subscriptions and message delivery.


Feature Details and Operation Guide

1. Authentication Method Comparison: Session vs JWT vs API Key

In enterprise architecture design, correctly distinguishing and selecting among the three authentication credentials is a prerequisite for data security and tenant isolation:

Comparison dimensionSession authentication (Cookie / Session Header)User JWT authentication (X-Appwrite-JWT)Server API Key (X-Appwrite-Key)
Applicable sideBrowser web apps, mobile apps (agentbase-web-sdk@2.10.0)Frontend calling enterprise self-hosted backend services, or accessing SQL Proxy user-mode APIsEnterprise backend microservices, scheduled jobs, agent orchestration backends (agentbase-node-sdk@2.10.0)
Issuance methodCalling login APIs such as createEmailPasswordSession and createOAuth2Session to generateLogged-in clients call account.createJWT() to generate dynamicallyOrganization administrators create it in the Console under Overview → API Keys
LifecycleDetermined by the project's Security → Session length setting (default 365 days, configurable in seconds/minutes/hours/days)Valid for a fixed 15 minutes; before expiry the client must re-issue it using a valid SessionCan be configured to never expire or with a specified expiry date, and can be revoked in the Console at any time
Permission evaluation modelStrictly follows the current user's Effective Roles (user:{id}, team:{id}/{role}, label:{name}) and resource ACLsFully consistent with the permissions of the user Session that issued the JWT, strictly constrained by table-level/row-level/file-level ACLsAuthorized by the Scopes checked for the Key; in regular data APIs it has the server-side admin perspective by default (not restricted by client-side row-level ACLs)
Browser exposure riskSafe (prefer HttpOnly Cookies bound to the domain platform)Short-lived token; only placed in request headers when the frontend sends requests to a trusted backendAbsolutely must not be placed in frontend code or public repositories; otherwise read/write access to the entire database would be leaked

2. Login Providers and Custom OAuth2 Configuration Guide

In the project's Auth → Settings tab, administrators can enable or disable basic login methods per business scenario and configure third-party OAuth2 providers:

Login method categorySpecific supported methodsKey behavior and applicable scenarios
Basic credential loginEmail and Password, Phone (SMS)The most commonly used login method for enterprise customers and internal employees; email addresses are automatically lowercased upon creation and validated for uniqueness within the project; phone numbers must be in E.164 format (e.g., +8613800138001).
Passwordless quick loginMagic URL, Email OTP (one-time email verification code)Users do not need to remember passwords; they can create a session by clicking a signed redirect link in an email or entering a 6-digit verification code, suitable for lightweight customer portals.
Anonymous session loginAnonymous (anonymous guest)Temporarily generates an anonymous User ID and session for unregistered visitors (role assigned to guests until conversion); users can later bind an email and password to smoothly upgrade to a formal registered account, retaining data associated with the existing session.
Standard and custom OAuth2GitHub, Google, Apple, Microsoft, Custom OAuth2, etc.Supports identity sources that implement the standard OAuth 2.0 Authorization Code flow.Custom OAuth2 supports no-code configuration for integrating enterprise self-hosted unified identity authentication (IdP) or platforms such as Gitee.

Steps to Configure Custom OAuth2 (Custom OAuth2 Provider)

  1. Register the application with the external identity source: Go to the enterprise unified identity platform (or an OAuth2 provider such as Gitee) to create an OAuth2 application, and record the issued Client ID and Client Secret.

  2. Go to the OAuth2 settings in the Console: In the project enterprise-ai-hub-210, click Auth → Settings in the left sidebar, scroll down to the OAuth2 Providers section, and click Custom OAuth2.

  3. Enable the toggle and fill in the endpoint and mapping parameters:

Configuration itemRequiredFormat and example values
EnabledYesSwitch to the enabled state to activate the Custom OAuth2 provider.
Client IDYesEnter the application client ID assigned by the identity provider, e.g., enterprise_sso_client_210.
Client SecretYesEnter the client secret (encrypted and stored on the server only; the plaintext is not displayed after saving).
Well-Known EndpointNoIf the identity source supports OIDC auto-discovery (e.g., https://idp.example.com/.well-known/openid-configuration), filling this in auto-populates the authorization and token endpoints.
Authorization EndpointYesThe OAuth2 authorization redirect address (must be a publicly reachable https:// address), e.g., https://gitee.com/oauth/authorize.
Token EndpointYesThe API address for exchanging the authorization code for an Access Token, e.g., https://gitee.com/oauth/token.
User Info EndpointYesThe API address for retrieving the user profile JSON, e.g., https://gitee.com/api/v5/user.
Email EndpointNoWhen the main User Info API does not directly return an email address, a separate email query API can be configured (e.g., https://gitee.com/api/v5/emails).
Client Authentication MethodYesSelect the client authentication method for the Token endpoint; supports client_secret_post (form-submitted secret) or client_secret_basic (Basic Auth header).
Subject / Email / Name / Email Verified field pathsYesDot-separated paths or decimal array indices for extracting fields from the JSON returned by User Info (or the Email Endpoint); complex expressions are not supported. When the domain is identified as gitee.com, the Console automatically suggests examples: Subject as id, Name as name, Email as 0.email. Note: the user's email is only marked as Verified when the Email Verified path explicitly returns the boolean value true.
  1. Register the Callback URI: Copy the fully generated callback address at the bottom of the dialog (in the form https://appbuild.oceanbase.com/v1/account/sessions/oauth2/callback/custom/<PROJECT_ID>) and paste it as-is into the allowed callback address whitelist of the external identity provider.

  2. Run the OAuth2 acceptance test in the Test tab:

    • Switch to the Auth → Test tab.

    • Confirm that the domain of the current access host is registered in the Web platform list of the project's Overview → Platforms.

    • Select an enabled OAuth2 provider, fill in the custom authorization scope (Scope) as needed, and click the Test OAuth2 login button to initiate a real redirect verification.

OAuth2 test page (reusing a registered screenshot)

Interface reference: reuses previously registered historical screenshots; demo data may differ from the current project; no new screenshots were taken this time.

Security and isolation mechanisms:

  • state The parameter is consumed once and strongly bound to the project ID, browser session, Callback address, Client ID, and server-side state revision; once an administrator modifies the OAuth2 configuration, all historical incomplete old state values become invalid immediately.

  • Test session isolation: End-user test sessions created by logging in via the Auth → Test tab are fully isolated from the administrator's current Console login state; clicking the logout button on the test page only destroys the end-user session under test and does not log the administrator out of the Console.

3. Permission Strings and Role System in Detail

Agentbase uses a unified declarative model of Permission (operation action) + Role (authorized principal role) to control resource access across Databases, Storage, and Messaging. The four basic permission actions are:

The table below lists all supported Role role expressions and their mapping rules in the SDK and the underlying storage:

Role typeSDK constructor expressionUnderlying role stringAuthorization matching logic and typical business scenarios
All visitors (including unauthenticated)Role.any()anyMatches any request (whether from a logged-in user or an anonymous unauthenticated request). Suitable for public knowledge base attachment downloads or public announcement table reads.
All unauthenticated/anonymous guestsRole.guests()guestsOnly matches guests or Anonymous sessions without a valid registered user session. Suitable for public form submission entry points.
All logged-in usersRole.users([status])users or users/verified, users/unverifiedMatches any logged-in end user within the project. When 'verified' is passed (i.e., Role.users('verified')), the user's email or phone number is required to be verified.
A specific single userRole.user(userId, [status])user:<USER_ID> (e.g., user:user_zhangwei_001)Only matches the end user with the specified User ID. Commonly used for customer_tickets row-level security, ensuring that customer Zhang Wei can only view the support tickets he submitted.
All members of a specified teamRole.team(teamId)team:<TEAM_ID> (e.g., team:team_support_ops)Matches any member who has joined the specified team (regardless of their role within the team). Suitable for departmental shared document libraries or team public boards.
Members with a specific role in a specified teamRole.team(teamId, role)team:<TEAM_ID>/<ROLE> (e.g., team:team_support_ops/admin)Only matches members holding a specific custom role (e.g., admin, support_lead) in the specified team. Suitable for permission-sensitive operations such as support ticket approval or knowledge base publishing.
A specified membership IDRole.member(membershipId)member:<MEMBERSHIP_ID>Precisely matches one specific team membership record (when a user leaves and rejoins a team, producing a new Membership ID, the old authorization automatically becomes invalid).
Users holding specific labelsRole.label(name)label:<LABEL_NAME> (e.g., label:vip, label:architect)Matches any end user whose labels array contains the label. Suitable for opening a high-priority support ticket channel or dedicated storage bucket access to all vip customers.

Server-side and Client-side SDK Permission Configuration Code Example

In the enterprise-ai-hub-210 project, when customer Zhang Wei (user_zhangwei_001) submits a customer support ticket, you can use @alipay/agentbase-sdk@2.10.0 (or agentbase-web-sdk@2.10.0) to attach the composite permission of "readable and writable by the owner + readable and processable by the VIP technical support team" to the ticket row:

import { Client, Databases, Permission, Role } from 'agentbase-web-sdk'; // Pin version @2.10.0

const client = new Client()
    .setEndpoint('https://appbuild.oceanbase.com/v1')
    .setProject('enterprise-ai-hub-210');

const databases = new Databases(client);

// Create a support ticket row and declare fine-grained row-level permissions (requires Row security enabled on the table)
const ticket = await databases.createDocument(
    'enterprise_biz_db',
    'customer_tickets',
    'TK-20261022-001',
    {
        title: 'OceanBase 向量索引在高并发混合检索下的 HNSW 参数调优咨询',
        status: 'open',
        priority: 'high',
        creatorUserId: 'user_zhangwei_001'
    },
    [
        // The submitter Zhang Wei himself has read and update permissions
        Permission.read(Role.user('user_zhangwei_001')),
        Permission.update(Role.user('user_zhangwei_001')),
        // All members of the VIP customer technical support group can read support tickets
        Permission.read(Role.team('team_support_ops')),
        // Only the admin role of the VIP customer technical support group can update or delete support tickets
        Permission.update(Role.team('team_support_ops', 'admin')),
        Permission.delete(Role.team('team_support_ops', 'admin'))
    ]
);

FAQ and Troubleshooting

Q1: Why do client-side calls to database or storage APIs return 401 User (role: guests) missing scope (account) or 401 user_unauthorized?

Root cause analysis:

  1. The request did not successfully carry the end user's login Session Cookie or the X-Appwrite-JWT request header, causing the server to identify the request as an unauthenticated guest (role: guests).

  2. In a cross-domain web application, the hostname currently accessed by the frontend has not been registered as a trusted Web Platform under Overview → Platforms in the project, causing the browser to block cross-domain cookies or fallback tokens.

  3. The target database table or storage bucket has not granted the corresponding read / write permissions to Role.any() or the Role.user(...) / Role.team(...) the current user belongs to.

Troubleshooting steps:

Q2: After configuring Custom OAuth2, what should I do when clicking the test login on the Auth → Test page reports an error Invalid state or the email is not marked as verified (Unverified)?

Root cause analysis:

  1. Invalid state: After the OAuth2 redirect was initiated, an administrator modified and re-saved the Custom OAuth2 configuration midway (triggering a server-side state revision increment), or the callback URL's hostname differs from the hostname used when the request was initiated.

  2. Email not marked as Verified: Custom OAuth2 requires that the configured Email Verified field path in the user JSON returned by the identity provider must strictly return a boolean true (a string "true", a number 1, or a missing field will not be treated as verified).

Troubleshooting steps:

Q3: How can backend support staff (e.g., Li Na user_lina_002) safely impersonate (Impersonate) the customer's perspective while investigating issues, without asking for the customer's password?

Root cause analysis and solution: Agentbase provides an audited and governed User Impersonation capability:

  1. The administrator goes to Auth → Users, opens the trusted senior support engineer account (e.g., user_lina_002 Li Na), and at the bottom of the Overview tab finds the User impersonation card and enables the toggle.

  2. Once enabled, when Li Na logs into her own account using the client SDK, she can specify the target user ID to impersonate in requests (e.g., user_zhangwei_001) to reproduce frontend support tickets or knowledge retrieval results from Zhang Wei's permission perspective.

  3. Security audit safeguards: For all requests initiated via impersonation, the underlying operation audit logs (Activity) are recorded under the account of the operator who initiated the impersonation. Enabling this toggle for ordinary external end users is strictly prohibited.

Q4: After modifying a user's team role (team:team_support_ops/admin) or user labels (label:vip), does the user need to log in again for the changes to take effect?

Answer: