Overview
The Auth Api provides a complete set of authentication-related features, supporting various log-in methods, user management, and session management. The Auth Api is divided into 7 categories by purpose. Each category contains related Api methods, helping developers quickly find suitable APIs depending on specific needs.
v3 version uses the open capability of Identity Verification HTTP API when calling relevant API for identity verification.
- Authentication Login: API methods for user registration and login, supporting various login methods.
- Session Management: API method to manage user session status and token.
- User Management: API methods to get, update and manage user information.
- Identity Source Management: API method to manage binding and unbinding of third-party identity sources.
- Password Management: API methods for password reset and modification.
- Verification Management: API methods for verification code sending, verify and resend.
- Other Tools: API methods for auxiliary features.
Basic Usage Examples
- Initialization Configuration
- Login Status Check
- User Registration Process
- User Logout
- Password Login
- Certification Status Listen
- Mobile Captcha Login
Publishable Key can go to Cloud Development Platform/API Key Configuration to generate
auth.detectSessionInUrl is an optional parameter for initialization. After configuration, it can automatically detect OAuth parameters (code, state) in the URL, suitable for usage scenarios such as signInWithOAuth and linkIdentity.
import cloudbase from "@cloudbase/js-sdk";
// Initialize it.
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
auth: {
detectSessionInUrl: true, // Option: automatically detect OAuth parameters in the URL, suitable for signInWithOAuth, linkIdentity
},
});
const auth = app.auth;
Check login status
async function checkAuthStatus() {
const { data, error } = await auth.getSession();
if (error) {
console.error("Check login status failed:", error.message);
return false;
}
if (data.session) {
console.log("user logged in:", data.session.user);
return true;
} else {
console.log("user not logged in");
return false;
}
}
// User registration example (four-step verification process)
async function registerUser(email, password, verificationCode) {
Step 1: Send verification.
const { data, error } = await auth.signUp({
email: email,
password: password,
});
if (error) {
console.error("send Captcha failed:", error.message);
return false;
} else {
console.log("Captcha has been sent, validating...");
Step 2: Verify the Captcha and complete registration
const { data: loginData, error: loginError } = await data.verifyOtp({
token: verificationCode,
});
if (loginError) {
console.error("verification failed:", loginError.message);
return false;
} else {
console.log("register successfully:", loginData.user?.email);
return true;
}
}
}
// User logout example
async function logoutUser() {
const { data, error } = await auth.signOut();
if (error) {
console.error("logout failed:", error.message);
return false;
} else {
console.log("logout successful, session purged");
return true;
}
}
// Password login example
async function loginWithPassword(email, password) {
const { data, error } = await auth.signInWithPassword({
email: email,
password: password,
});
if (error) {
console.error("login failed:", error.message);
return false;
} else {
console.log("login successful:", data.user?.email);
return true;
}
}
// Listen to authentication status transition
auth.onAuthStateChange((event, session, info) => {
console.log("Authentication Status Transition:", event);
switch (event) {
case "INITIAL_SESSION":
console.log("initial session established");
if (session) {
console.log("user logged in:", session.user);
} else {
console.log("user not logged in");
}
break;
case "SIGNED_IN":
console.log("user login successful:", session.user);
break;
case "SIGNED_OUT":
console.log("user logged out");
break;
case "PASSWORD_RECOVERY":
console.log("password reset");
break;
case "TOKEN_REFRESHED":
console.log("Token refreshed");
break;
case "USER_UPDATED":
console.log("user information updated");
break;
case "BIND_IDENTITY":
console.log("identity source binding result");
break;
}
});
Complete mobile captcha login page implementation
class PhoneLoginPage {
constructor() {
this.setupEventListeners();
}
// Set up event listening
setupEventListeners() {
document.getElementById("sendCodeBtn").addEventListener("click", (e) => {
e.preventDefault();
this.sendVerificationCode();
});
document.getElementById("verifyCodeBtn").addEventListener("click", (e) => {
e.preventDefault();
this.verifyCodeAndLogin();
});
}
// Send verification code
async sendVerificationCode() {
const phone = document.getElementById("phone").value;
if (!phone) {
alert("Enter your phone number");
return;
}
// Verify phone number format
if (!this.validatePhone(phone)) {
alert("Enter a valid mobile number format");
return;
}
// Display loading...
this.showLoading(true);
this.hideError();
try {
const { data, error } = await auth.signInWithOtp({
phone: phone,
});
if (error) {
this.handleSendCodeError(error);
} else {
this.handleSendCodeSuccess(data);
}
} catch (error) {
this.handleNetworkError(error);
} finally {
this.showLoading(false);
}
}
// Verify the Captcha and log in
async verifyCodeAndLogin() {
const code = document.getElementById("code").value;
if (!code) {
alert("Please enter Captcha");
return;
}
if (!this.verifyFunction) {
alert("Please first send Captcha");
return;
}
this.showLoading(true);
this.hideError();
try {
const { data, error } = await this.verifyFunction({ token: code });
if (error) {
this.handleVerifyError(error);
} else {
this.handleLoginSuccess(data);
}
} catch (error) {
this.handleNetworkError(error);
} finally {
this.showLoading(false);
}
}
// Verify phone number format
validatePhone(phone) {
const phoneRegex = /^1[3-9]\d{9}$/;
return phoneRegex.test(phone);
}
// Handle send verification code success
handleSendCodeSuccess(data) {
this.verifyFunction = data.verifyOtp;
// Display the Captcha input area
document.getElementById("verificationSection").style.display = "block";
document.getElementById("phoneSection").style.display = "none";
// Countdown starts
this.startCountdown(60);
document.getElementById("success").innerText =
The Captcha has been sent to your mobile phone. Please check your inbox.
document.getElementById("success").style.display = "block";
}
// Handle send verification error
handleSendCodeError(error) {
switch (error.code) {
case "invalid_phone":
document.getElementById("error").innerText =
Incorrect phone number format, please check and retry.
break;
case "user_not_found":
document.getElementById("error").innerText =
This phone number is unregistered. Please first register or use another mobile number.
break;
case "resource_exhausted":
document.getElementById("error").innerText = "Sending frequency too high, try again later";
break;
case "unreachable":
document.getElementById("error").innerText =
network connection failed, check the network settings
break;
default:
document.getElementById("error").innerText =
"send Captcha failed: " + error.message;
}
document.getElementById("error").style.display = "block";
}
// Handle verification error
handleVerifyError(error) {
switch (error.code) {
case "invalid_code":
document.getElementById("error").innerText = "Captcha error, please enter again";
break;
case "code_expired":
document.getElementById("error").innerText = "Captcha expired, please obtain again";
// Display the resend button
document.getElementById("resendBtn").style.display = "block";
break;
case "max_attempts_exceeded":
document.getElementById("error").innerText = "Too many verification attempts, try again later";
break;
default:
document.getElementById("error").innerText =
"verification failed: " + error.message;
}
document.getElementById("error").style.display = "block";
}
handle successful login
handleLoginSuccess(data) {
document.getElementById("success").innerText = "Login successful. Welcome back";
document.getElementById("success").style.display = "block";
console.log("user information:", data.user);
console.log("session information:", data.session);
Navigate to the homepage after a delay
setTimeout(() => {
window.location.href = "/dashboard";
}, 2000);
}
// Handle network error
handleNetworkError(error) {
document.getElementById("error").innerText =
Network error, check the network connection and try again.
document.getElementById("error").style.display = "block";
console.error("network error:", error);
}
// Show/Hide loading...
showLoading(show) {
document.getElementById("loading").style.display = show ? "block" : "none";
document.getElementById("sendCodeBtn").disabled = show;
document.getElementById("verifyCodeBtn").disabled = show;
}
// Hide error info
hideError() {
document.getElementById("error").style.display = "none";
}
// Countdown starts
startCountdown(seconds) {
let countdown = seconds;
const btn = document.getElementById("resendBtn");
const originalText = btn.innerText;
btn.disabled = true;
const timer = setInterval(() => {
countdown--;
btn.innerText = `${countdown}s to resend`;
if (countdown <= 0) {
clearInterval(timer);
btn.disabled = false;
btn.innerText = originalText;
}
}, 1000);
}
}
// Initialize upon page loading completion
window.addEventListener("DOMContentLoaded", () => {
new PhoneLoginPage();
});
Authentication login
signUp
async signUp(params: SignUpReq): Promise<SignUpRes>
Register a new user account, implement intelligent registration and login process.
Phone number verification code registration is only supported in the Shanghai region
-Create a new user account -Implement intelligent registration and login process: send verification code → wait for user input → intelligently determine user existence → automatically log in or register and sign in. -If the user already exists, log in directly. If the user does not exist, register a new user and automatically log in.
参数
返回
示例
signInAnonymously
async signInAnonymously(params?: SignInAnonymouslyReq): Promise<SignInRes>
Anonymous login, create a temporary anonymous user account.
-Create a temporary anonymous user account -No need to provide any authentication information
- Suitable for scenarios where temporary access permission is required -Before using, please confirm that anonymous login (enabled by default) is enabled in Cloud Development Platform/Identity Verification/Registration Configuration.
参数
返回
示例
signInWithPassword
async signInWithPassword(params: SignInWithPasswordReq): Promise<SignInRes>
Log in with username, email, or mobile number and password.
-Support username, mailbox, or mobile number in conjunction with password as login methods (choose one). -Before using, please confirm that username and password login (enabled by default) is enabled in Cloud Development Platform/Identity Verification/Regular Login.
参数
返回
示例
signInWithOtp
async signInWithOtp(params: SignInWithOtpReq): Promise<SignInWithOtpRes>
Use one-time password (OTP) for login validation, supporting mailbox and SMS verification.
SMS verification code is only supported in the Shanghai region
- Log in with one-time verification code sent to your mailbox or mobile number
- Support the complete verification process: send verification code → wait for user input → verify and log in.
- Suitable for passwordless login scenarios, offering higher security
- Before using, please confirm that mailbox/SMS Captcha login is enabled in Cloud Development Platform/Identity Verification/Log-in Methods/Regular Login.
- If the user does not exist, a default registered user will be created. The automatic creation of the user can be controlled through the
shouldCreateUserparameter, which is set to true by default - For email login, you can use the
emailRedirectToparameter to specify a callback URL, enabling Magic Link login. Users can click the link in the email to complete login
参数
返回
示例
signInWithOAuth
async signInWithOAuth(params: SignInWithOAuthReq): Promise<SignInOAuthRes>
Generate authorization links for third-party platforms, supporting mainstream platforms such as WeChat and Google.
-Generate the authorization page URL for third-party platforms such as WeChat and Google. -Store status information in the browser session so that it can be verified subsequently -Support custom callback address and status parameter -Before using, please confirm that the corresponding OAuth identity source is enabled in Cloud Development Platform/Identity Verification/Log-in Methods.
Notes
-After calling this method, the status information is automatically saved to the browser session. When auth.detectSessionInUrl is set to true in cloudbase.init, verifyOAuth is automatically called for verification upon returning from a third-party callback, otherwise manually verify via the verifyOAuth method subsequently.
- If no state parameter is provided, the system automatically generates a status parameter in the format
prd-{provider}-{random string}. -The callback URL needs to be configured in the protected domains of the Cloud Development Platform, otherwise it will return a permission error.
参数
返回
示例
signInWithIdToken
async signInWithIdToken(params: SignInWithIdTokenReq): Promise<SignInRes>
Log in using a third-party platform identity token, supporting mainstream platforms such as WeChat and Google.
-Log in using a third-party platform identity token, such as WeChat and Google.
- Support specifying third-party platform flags. Third-party platforms must first be configured in Cloud Development Platform/Identity Verification/Log-in Methods.
- Token is a required parameter
参数
返回
示例
signInWithCustomTicket
async signInWithCustomTicket(getTickFn: GetCustomSignTicketFn): Promise<SignInRes>
Use custom login invoice to log in, support completely custom login process.
-Use custom login ticket to authenticate, login ticket creation can be performed on the server side using Create Custom Login Ticket API -Support passing functions to obtain custom login invoice -Suitable for scenarios where a fully custom login process is required
- The detailed process of issuing a Ticket can be found in Custom Login
参数
functions to obtain custom login invoice, return Promise<string>
返回
示例
signInWithOpenId
async signInWithOpenId(params?: SignInWithOpenIdReq): Promise<SignInRes>
WeChat mini program OpenID silent sign-in. If the user does not exist, it will determine whether to automatically register based on the login mode configuration of the corresponding identity source in the Cloud Development Platform login methods (https://tcb.cloud.tencent.com/dev?envId=#/identity/login-manage).
Only supported for use in WeChat mini program
参数
Login parameters
返回
示例
signInWithPhoneAuth
async signInWithPhoneAuth(params: SignInWithPhoneAuthReq): Promise<SignInRes>
WeChat mini program mobile phone authorization sign-in. If the user does not exist, it will determine whether to automatically register based on the login mode configuration of the corresponding identity source in the Cloud Development Platform login methods (https://tcb.cloud.tencent.com/dev?envId=#/identity/login-manage).
Only supported for use in WeChat mini program
参数
Login parameters
返回
示例
Session Management
getSession
async getSession(): Promise<SignInRes>
Get current session info and check user login status.
-Get current user session information, including access token and user information. -Check whether the user is logged in, return empty conversation if not logged in
参数
无参数
返回
示例
refreshSession
async refreshSession(refresh_token?: string): Promise<SignInRes>
Refresh the session token, extend the user login status, support auto-renewal and error recovery.
-Use a refresh token to get a new access token -Extend the valid period of user sessions -Supports the use of designated refresh token or default token
参数
返回
示例
setSession
async setSession(params: SetSessionReq): Promise<SignInRes>
Use existing access token and refresh token to set user session, support external system integration and manual session management.
-Use existing access_token and refresh_token to set user session -Suitable for scenarios where tokens are obtained from an external system and sessions are set manually. -Set session successfully to trigger SIGNED_IN event
参数
返回
示例
signOut
async signOut(params?: SignOutReq): Promise<SignOutRes>
User logout, purge current session and local storage.
-Log out current user login status securely -Purge server-side session and local storage -Support redirect to specified page
- Trigger authentication status change events
参数
返回
示例
User Management
getUser
async getUser(): Promise<GetUserRes>
Obtain currently logged in user detailed information, including identity information, metadata and permission status, support users material show and access verification.
-Obtain currently logged in user complete information -including basic user information, metadata and identity information Users are advised to be logged in to obtain the complete information -Support user check, permission and status verification
参数
无参数
返回
示例
refreshUser
async refreshUser(): Promise<CommonRes>
Refresh current logged-in user information.
-Refresh current logged-in user complete information
- Re-fetch the latest user data from the server
- Suitable for scenarios where user information may be updated but local cache remains unsynced User must be logged in to refresh information
参数
无参数
返回
示例
updateUser
async updateUser(params: UpdateUserReq): Promise<GetUserRes>
Update current logged-in user information.
-Update password not supported. Please use resetPasswordForEmail, resetPasswordForOld or reauthenticate to update password. -Update current logged-in user basic info and metadata -Support updating mailbox, mobile number, username, Nickname, avatar, etc. -User must be logged in to update information Return upon success with updated user information
参数
返回
示例
deleteUser
async deleteUser(params: DeleteMeReq): Promise<CommonRes>
Delete the account of the current logged-in user.
-Permanently delete the account of the current logged-in user. -Verify user password to confirm identity. -Once deleted, ALL user data will be permanently removed. -This operation is irreversible. Use with caution.
参数
返回
示例
Identity Source Management
getUserIdentities
async getUserIdentities(): Promise<GetUserIdentitiesRes>
Retrieve all identity sources bound to the current user.
- Retrieve all third-party identity sources. Related identity sources can be configured in Cloud Development Platform/Identity Verification/Log-in Methods. -Return detailed information of the identity source, including platform identifier, identity source ID and binding time. -User logged in status is required to retrieve identity source information.
参数
无参数
返回
示例
linkIdentity
async linkIdentity(params: LinkIdentityReq): Promise<LinkIdentityRes>
Bind a new identity source to the current user, and it will automatically redirect to the third-party OAuth authorization page.
- Bind a new third-party identity source to the current logged-in user. It supports binding third-party platforms such as WeChat, Google, and GitHub. The identity source must first be configured in Cloud Development Platform/Identity Verification/Login Methods.
- After binding succeeded, the identity source is usable by users to log in.
- User logged in status is required to bind an identity source
-Set
auth.detectSessionInUrltotruein cloudbase.init, and verifyOAuth will automatically verify after returning from a third-party callback, otherwise manually call the verifyOAuth method subsequently.
参数
返回
示例
unlinkIdentity
async unlinkIdentity(params: UnlinkIdentityReq): Promise<CommonRes>
Unbind the identity source bound to the current user.
- Unbind the third-party identity source bound to the current logged-in user. Related identity sources can be configured in Cloud Development Platform/Identity Verification/Log-in Methods.
- Unbinding is successful. Reload the identity source list.
- Use the identity source flag (provider) instead of the identity source ID (identity_id) to proceed with unbinding.
参数
返回
示例
Password Management
resetPasswordForEmail
async resetPasswordForEmail(email: string): Promise<ResetPasswordForEmailRes>
Reset user password via mailbox using a four-step verification process.
-Send verification code via mailbox to reset user password -Use a four-step verification process: send verification code → wait for user input → verify verification code → set new password. -The user email must be registered and verified.
参数
User registration email address
返回
示例
resetPasswordForOld
async resetPasswordForOld(params: ResetPasswordForOldReq): Promise<SignInRes>
Reset the password of the current logged-in user with the old password.
-Reset the password of the current logged-in user by verifying the old password. -User must be logged in. -Suitable for scenarios where users remember the old password
参数
返回
示例
reauthenticate
async reauthenticate(): Promise<ReauthenticateRes>
Re-authenticate the current logged-in user identity, verify with Captcha and allow password change.
SMS verification code is only supported in the Shanghai region
-Re-authenticate the present logged-in user identity and support password update. -Verify by sending a verification code to the user's registered mailbox or mobile number, giving priority to the mailbox. If the user has not set a mailbox, use the mobile number. -Applicable to identity verification before security-sensitive operations
参数
无参数
返回
示例
Verification Management
verifyOAuth
async verifyOAuth(params?: VerifyOAuthReq): Promise<VerifyOAuthRes>
Verify the third-party platform authorization callback and complete the OAuth login process.
-Verify the third-party platform authorization callback, retrieve user information, complete login, and use in conjunction with signInWithOAuth. -Support auto retrieval of authorization code and status parameter from URL parameter -Provide a complete security verification mechanism to prevent CSRF attacks
参数
返回
示例
verifyOtp
async verifyOtp(params: VerifyOtpReq): Promise<SignInRes>
Verify the one-time password (OTP) to complete login or sign-up process.
SMS verification code is only supported in the Shanghai region
-Verify the one-time password (OTP) sent to your mailbox or mobile number. -Support two verification methods: mailbox or mobile number (choose one)
- Automatically log in the user and return session information after successful verification
- Suitable for registration, login, and password reset scenarios
参数
返回
示例
resend
async resend(params: ResendReq): Promise<ResendRes>
Resend Captcha to mailbox or phone number.
SMS verification code is only supported in the Shanghai region
-Resend verification code to user's mailbox or mobile number -Support registration, mailbox update, mobile number change, and other scenarios. -Resend to get a new message ID for verification process -Provide rate limit protection to prevent malicious resend
参数
返回
示例
Other tools
onAuthStateChange
onAuthStateChange(callback: OnAuthStateChangeCallback): OnAuthStateChangeResult
Listen to authentication status changes and respond to events such as logon, logout, and token refresh in real time.
-Listen to user authentication status change events -Support various event types: logon, log out, token refresh, user information update, identity source bind. -Return the subscription object for cancel listening
- Suitable to build responsive UI and status management
参数
Status change callback function
返回
示例
getClaims
async getClaims(): Promise<GetClaimsRes>
Retrieve the claim info from the current access token for debug and permission check.
-Parse the JWT claim info from the current access token. -Return the header, declaration, and signature of the token. -Debug token info, check permissions, and verify token status. -Users are advised to be logged in to obtain token info
参数
无参数
返回
示例
toDefaultLoginPage
async toDefaultLoginPage(params: authModels.ToDefaultLoginPage): Promise<void>
Redirect to the default login page, fully compatible with web and WeChat mini program.
-Support redirection to the system default login page -Compatible with Web and WeChat mini program.
- Configurable login page version and redirect address -Support redirect with custom parameters
Debug locally
If you develop a Web application, since the static resources of the __auth login page are stored in Website Hosting, you need to configure a proxy during local debugging to successfully redirect to the __auth login page.
Recommended to use the Whistle tool to configure proxy. The access domain of the __auth login page can be viewed in Static Website Hosting - Configuration Message - Default Domain Name.
Assuming the access address of the locally started application is http://localhost:3000 and the access domain of the __auth login page is lowcode-xxx-xxx.tcloudbaseapp.com, the Rules configuration of the Whistle proxy is as follows:
https://lowcode-xxx-xxx.tcloudbaseapp.com http://localhost:3000
# Configure proxy for other application paths
After running the application, it can be accessed via https://lowcode-xxx-xxx.tcloudbaseapp.com
参数
返回
示例
Error Code
Login error
| Error Code | Description |
|---|---|
| not_found | user does not exist |
| password_not_set | The current user has not set a password. Please use Captcha to log in or third-party login method |
| invalid_password | Incorrect Password |
| user_pending | user not activated |
| user_blocked | user disabled |
| invalid_status | Exceeds the maximum number of retries for password, try again later |
| invalid_two_factor | Captcha mismatch or outdated |
Registration error
| Error Code | Description |
|---|---|
| failed_precondition | The phone number or mailbox you input has been registered, please use another number |
Captcha-related errors
| Error Code | Description |
|---|---|
| failed_precondition | failed to obtain user information from third party |
| resource_exhausted | Your attempts are too frequent, try again later |
| invalid_argument | The input verification code is incorrect or expired |
| aborted | Too many attempts, go back to the first page and try again later |
| permission_denied | Your current session expired, return and retry |
| captcha_required | Captcha is required, based on robot service access |
| captcha_invalid | Incorrect Captcha, based on robot service access |
Other Errors
| Error Code | Description |
|---|---|
| unreachable | Network error, check your network connection and try again later |
Error Description
| Error Code | Error Description | Description |
|---|---|---|
| permission_denied | cors permission denied, check if {url} is in your client {env} domains | please check whether it has been configured in "cloud Development Platform/Environment Configuration/Secure source/Protected domains" (https://tcb.cloud.tencent.com/dev?envId=#/env/safety-source) for the corresponding {env} environment. It will take effect 10 minutes after configuration. |
Complete type definition
SignInAnonymouslyReq
// Anonymous login parameters
interface SignInAnonymouslyReq {
provider_token?: string; // token (optional)
}
User
interface User {
id: any; // User ID
aud: string; // Audience
role: string[]; // user role
email: any; // Email
email_confirmed_at: string; // Email confirmation time
phone: any; // Phone number
phone_confirmed_at: string; // Mobile number confirmation time
confirmed_at: string; // Confirmation time
last_sign_in_at: string; // Last login time
app_metadata: {
app_metadata: {
provider: any; // Provider
providers: any[]; // Provider list
};
user_metadata: {
user_metadata: {
name: any; // Name
picture: any; // Avatar
username: any; // Username
gender: any; // Gender
locale: any; // Region
uid: any; // User ID
nickName: any; // Nickname
avatarUrl: any; // Avatar URL
location: any; // Location
hasPassword: any; // Whether there is a password
};
identities: any; // Identity information
created_at: string; // Creation time
updated_at: string; // Update time
is_anonymous: boolean; // Whether the user is anonymous
// Add a field.
recovery_sent_at?: string; // Password reset send time
email_change_sent_at?: string; // Email change send time
phone_change_sent_at?: string; // Phone number change send time
new_email?: string; // New email address
new_phone?: string; // New phone number
}
Session
interface Session {
access_token: string; // Access token
refresh_token: string; // Refresh token
expires_in: number; // Expiration time (seconds)
token_type: string; // Token type
user: User; // User information
// Add a field.
provider_token?: string; // Third-party platform token
provider_refresh_token?: string; // Third-party platform refresh token
expires_at?: number; // Expiry timestamp
issued_at?: number; // Issuance timestamp
scope?: string; // Authorization scope
token_id?: string; // Token ID
}
AuthError
// Authentication error type
interface AuthError extends Error {
code: (string & {}) | undefined; // Error code
requestId?: string; // Request ID
status: number | undefined; // HTTP Status Code
// Common error codes
// 400: Client Error
// - invalid_email: Incorrect email format
// - invalid_phone: Incorrect phone number format
// - invalid_password: Invalid password format
// - user_not_found: user does not exist
// - email_already_exists: Email already exists
// - phone_already_exists: Phone number already exists
// - username_already_exists: Username already exists
// - invalid_code: Invalid verification code
// - code_expired: Captcha expired
// - max_attempts_exceeded: Too many verification attempts
// - password_too_weak: Password strength is insufficient
// - invalid_token: Token invalid
// - token_expired: Token expired
// - state_mismatch: State parameter mismatch
// - provider_not_supported: Unsupported third-party platform
// - provider_mismatch: Third-party platform flag mismatch
// - failed_precondition: Prerequisite failed
// - permission_denied: Insufficient permissions
// - resource_exhausted: Resource exhaustion
// - unreachable: Network connection failed
// 500: Server Error
// - internal_error: Internal Server Error
// - service_unavailable: Service unavailable
}
CommonRes
// Common response parameters
interface CommonRes {
data: {}; // An empty object when successful
error: AuthError | null; // error information, null if successful
}
SignUpReq
// User registration parameters (four-step verification process)
interface SignUpReq {
email?: string; // Email address (optional, choose either this or a phone number)
phone?: string; // Mobile number (optional, choose either this or a mailbox)
password: string; // Password (required)
username?: string; // Username (optional), length 5-24 characters, supports Chinese and English letters, digits, and special characters (only _- allowed). Chinese characters are not allowed.
nickname?: string; // Nickname (optional)
avatar_url?: string; // Avatar URL (optional)
gender?: "MALE" | "FEMALE"; // Gender (optional)
}
SignOutReq
// User logout parameters
interface SignOutReq {
options?: {
// Configuration options (optional)
redirectTo?: string; // Redirection address after log out
clearStorage?: boolean; // Whether to clear local storage (default true)
};
}
SignInWithPasswordReq
// Password login parameters
interface SignInWithPasswordReq {
username?: string; // Username (optional, selectable with mailbox or phone number), length 5-24 characters, supports Chinese and English letters, digits, and special characters (only _- allowed). Chinese characters are not allowed.
email?: string; // Email address (optional, choose either this, a username, or a phone number)
phone?: string; // Mobile number (optional, choose either this, a username, or a mailbox)
password: string; // Password (required)
is_encrypt?: boolean; // Encrypted or not; default false
}
SignInWithIdTokenReq
// ID-token login parameters
interface SignInWithIdTokenReq {
provider?: string; // Third-party platform flag (optional)
token: string; // Third-party platform identity token (required)
// Add a field.
provider?: string; // Third-party platform flag (optional, duplicate parameter with provider, reserved for compatibility)
}
SignInWithOtpReq
// OTP login parameters
interface SignInWithOtpReq {
email?: string; // Email address (optional, choose either this or a phone number)
phone?: string; // Mobile number (optional, choose either this or a mailbox)
options?: {
shouldCreateUser?: boolean; // If the user does not exist, create a new user, default true
emailRedirectTo?: string; // email redirect url (optional)
};
}
SignInWithOAuthReq
// OAuth authorization parameter
interface SignInWithOAuthReq {
provider: string; // Third-party platform flag (required)
options?: {
// Configuration options (optional)
redirectTo?: string; // Callback URL, defaults to current page
skipBrowserRedirect?: boolean; // Whether to navigate to the authorization page, false by default
state?: string; // Status parameter, used for security verification, defaults to a random string (format: prd-{provider}-{random string})
queryParams?: Record<string, string>; // Additional query parameters, merged into the authorization URI
type?: "sign_in" | "bind_identity"; // Type (optional), defaults to 'sign_in', sign_in: sign in, bind_identity: bind identity
};
}
SetSessionReq
// Session setting parameters
interface SetSessionReq {
access_token: string; // Access token (required)
refresh_token: string; // Refresh token (required)
}
VerifyOAuthReq
// OAuth verification parameter
interface VerifyOAuthReq {
code?: string; // Authorization code (optional, default from URL parameter access)
state?: string; // Status parameter (optional, default from URL parameter access)
provider?: string; // Third-party platform flag (optional, default from session retrieval)
}
VerifyOtpReq
// OTP verification parameters
interface VerifyOtpReq {
type?:
| "sms"
| "phone_change"
| "signup"
| "invite"
| "magiclink"
| "recovery"
| "email_change";
email; // Validation type (optional)
email?: string; // Email address (optional, choose either this or a phone number)
phone?: string; // Mobile number (optional, choose either this or a mailbox)
token: string; // Captcha (required)
messageId: string; // ID corresponding to the verification code (required)
}
UpdateUserReq
// User information update parameter
interface UpdateUserReq {
email?: string; // Email address
phone?: string; // Phone number
username?: string; // Username (optional), length 5-24 characters, supports Chinese and English letters, digits, and special characters (only _- allowed). Chinese characters are not allowed.
description?: string; // Description (optional)
avatar_url?: string; // Avatar URL (optional)
nickname?: string; // Nickname (optional)
gender?: "MALE" | "FEMALE"; // Gender (optional)
}
LinkIdentityReq
// Identity source bind parameter
interface LinkIdentityReq {
provider: string; // Identity source flag (required)
}
UnlinkIdentityReq
// Identity source unbind parameter
interface UnlinkIdentityReq {
provider: string; // Identity source flag (required)
}
ReauthenticateReq
// Re-authenticate parameter
interface ReauthenticateReq {
// No input parameters, use the current logged-in user's info
}
ResendReq
// Resend verification code parameter
interface ResendReq {
email?: string; // Email address (optional, choose either this or a phone number)
phone?: string; // Mobile number (optional, choose either this or a mailbox)
type?: "signup" | "email_change" | "phone_change" | "sms"; // Type (optional)
}
ResendRes
// Resend verification code response parameter
interface ResendRes {
data: {
messageId?: string; // message ID (verification code ID)
};
error: AuthError | null; // error information, null if successful
}
SignInWithOtpRes
// OTP login response parameters
interface SignInWithOtpRes {
data: {
verifyOtp?: (params: {
token: string;
messageId?: string;
}) => Promise<SignInRes>; // Captcha callback function, supports messageId parameter
};
error: AuthError | null; // error information, null if successful
}
SignUpRes
// User registration response parameters
interface SignUpRes {
data: {
verifyOtp?: (params: {
token: string;
messageId?: string;
}) => Promise<SignInRes>; // Captcha callback function, supports messageId parameter
};
error: AuthError | null;
}
SignInOAuthRes
// OAuth authorization response parameters
interface SignInOAuthRes {
data: {
url?: string; // Authorization page URL
provider?: string; // Third-party platform flag
scopes?: string; // Authorization scope
};
error: AuthError | null; // error information, null if successful
}
LinkIdentityRes
// Identity source bind response parameter
interface LinkIdentityRes {
data: {
provider?: string; // Bound identity source flag
type?: "sign_in" | "bind_identity" | ""; // Type (optional), defaults to 'sign_in', sign_in: sign in, bind_identity: bind identity
};
error: AuthError | null; // error information, null if successful
}
Identity
interface Identity {
id: string; // Identity source flag
name: string; // Identity source name
picture: string; // Avatar URL
}
GetUserIdentitiesRes
// User identity source retrieval response parameter
interface GetUserIdentitiesRes {
data: {
identities?: Array<{
id: string; // Identity source flag
name: string; // Identity source name
picture: string; // Avatar URL
}>;
};
error: AuthError | null; // error information, null if successful
}
GetClaimsRes
// Declaration information acquisition response parameter
interface GetClaimsRes {
data: {
// token declaration info
claims?: {
iss: string; // issuer
sub: string; // subject
aud: string; // audience
exp: number; // expiration time
iat: number; // issued at
at_hash: string; // access token hash
name: string; // Name
picture?: string; // Avatar URL
email?: string; // Email
phone_number?: string; // Phone number
scope: string; // Authorization scope
project_id: string; // Project ID
provider?: string; // Third-party platform flag
provider_type?: string; // Third-party platform type
groups?: string[]; // User group
meta?: {
wxOpenId?: string;
wxUnionId?: string;
};
user_id: string; // uid
roles: string[]; // role
user_type: string; // Type of user
client_type: string; // Client type
is_system_admin: boolean; // System admin
};
// token header information
header?: {
alg: string; // Encryption algorithm
kid: string; // Token ID
};
signature?: string; // Token signature
};
error: AuthError | null; // error information, null if successful
}
ResetPasswordForOldReq
// Reset the password parameter with the old password
interface ResetPasswordForOldReq {
new_password: string; // New password (required)
old_password: string; // Old password (required)
}
DeleteMeReq
// Delete current user parameters
interface DeleteMeReq {
password: string; // User password (required)
}
SignInRes
// Login response parameters
interface SignInRes {
data: {
user?: User; // User information
session?: Session; // Session information
};
error: AuthError | null; // error information, null if successful
}
GetUserRes
// User information retrieval response parameter
interface GetUserRes {
data: {
user?: User; // User details
};
error: AuthError | null; // error information, null if successful
}
OnAuthStateChangeEvent
// Authentication status change event type
type OnAuthStateChangeEvent =
| "SIGNED_OUT" // User logged out
| "SIGNED_IN" // User login successful
| "INITIAL_SESSION" // Initial session established
| "PASSWORD_RECOVERY" // Password reset
| "TOKEN_REFRESHED" // Token refreshed
| "USER_UPDATED" // User information updated
| "BIND_IDENTITY"; // Identity source binding result
OnAuthStateChangeCallback
// Authentication status change callback function type
type OnAuthStateChangeCallback = (
event: OnAuthStateChangeEvent,
session: Session
) => void;
ResetPasswordForEmailRes
// Mailbox password reset response parameter
interface ResetPasswordForEmailRes {
data: {
updateUser?: (attributes: UpdateUserAttributes) => Promise<SignInRes>; // Captcha callback function, supports new password parameter
};
error: AuthError | null; // error information, null if successful
}
UpdateUserAttributes
// User attribute update parameter
interface UpdateUserAttributes {
nonce: string; // Captcha
password: string; // New password
}
ReauthenticateRes
// Re-authenticate response parameter
interface ReauthenticateRes {
data: {
updateUser?: (attributes: UpdateUserAttributes) => Promise<SignInRes>; // Captcha callback function, supports new password parameter
};
error: AuthError | null; // error information, null if successful
}