Skip to main content

authentication_v3

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.


Basic Usage Examples

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, // Optional: automatically detect OAuth parameters in the URL, suitable for signInWithOAuth, linkIdentity
},
});

const auth = app.auth;

Authentication login

signUp

async signUp(params: SignUpReq): Promise<SignUpRes>

Register new user account, use intelligent signup and login process.

Note

Phone number verification code registration is only supported in the Shanghai region

-Create a new user account -Use intelligent signup and login process: send verification code → wait for user input → intelligently determine user existence → automatically log in or register and log in. -If the user already exists, log in directly. If the user does not exist, register a new user and automatically log in.

参数

params
SignUpReq

返回

Promise
SignUpRes

示例

Step one: Send a verification code to the mailbox and store verificationInfo.
const { data, error } = await auth.signUp({
email: "newuser@example.com",
password: "securePassword123",
username: "newuser",
});

if (error) {
console.error("Send Captcha failed:", error.message);
} else {
console.log("verification code sent to email, waiting for user input...");

Step 2: Wait for user input of Captcha (wrap the user input event with Promise)
const verificationCode = "123456"; // user input

Step 3: Intelligent verification process (automatically determine user existence)
const { data: loginData, error: loginError } = await data.verifyOtp({
token: verificationCode,
});

if (loginError) {
console.error("Verification failed:", loginError.message);
} else {
Step 4: Automatically complete registration or log in
console.log("Operation succeeded, user information:", loginData.user);
console.log("session information:", loginData.session);
console.log(
"The system has automatically determined: "
loginData.user?.email ? "New user registration and log in" : "Existing users log in directly"
);
}
}

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.

参数

params
SignInAnonymouslyReq

返回

Promise
SignInRes

示例

Create an anonymous user
const { data, error } = await auth.signInAnonymously();

if (error) {
console.error("Anonymous login failed:", error.message);
console.error("error code:", error.code);
} else {
console.log("anonymous login success");
console.log("anonymous user ID:", data.user?.id);
console.log("session information:", data.session);
console.log("whether anonymous user:", data.user?.is_anonymous);
}

signInWithPassword

async signInWithPassword(params: SignInWithPasswordReq): Promise<SignInRes>

Log in with userName, mailbox, or phone number and password.

-Support username, mailbox, or mobile number in conjunction with password as log-in 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.

参数

params
SignInWithPasswordReq

返回

Promise
SignInRes

示例

const { data, error } = await auth.signInWithPassword({
username: "testuser",
password: "password123",
});

if (error) {
console.error("Login failed:", error.message);
} else {
console.log("Login successful, user information:", data.user);
console.log("session information:", data.session);
}

signInWithOtp

async signInWithOtp(params: SignInWithOtpReq): Promise<SignInWithOtpRes>

Use one-time password (OTP) for login validation, supporting mailbox and SMS verification.

Note

SMS verification code is only supported in the Shanghai region

-Send a one-time verification code via mailbox or mobile number for login validation. -Support the full verification process: send Captcha → wait for user input → verify and log in. -Suitable for passwordless login scenarios, offering higher security -Before using, please confirm that log in via mailbox/SMS verification code is enabled in Cloud Development Platform/Identity Verification/Log-in Methods/Regular Login.

参数

params
SignInWithOtpReq

返回

Promise
SignInWithOtpRes

示例

const { data, error } = await auth.signInWithOtp({
phone: "13800138000",
});

if (error) {
console.error("Send Captcha failed:", error.message);
} else {
console.log("verification code sent, waiting for user input...");

// Verify the Captcha after user input
const { data: loginData, error: loginError } = await data.verifyOtp({
token: "123456",
});

if (loginError) {
console.error("Verification failed:", loginError.message);
} else {
console.log("Login successful:", loginData.user);
console.log("session information:", loginData.session);
}
}

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 follow-up verification

Must-Knows

  • After calling this method, status information will be automatically saved to the browser session. When setting auth.detectSessionInUrl to true in cloudbase.init, it will automatically call verifyOAuth to verify after returning from a third-party callback, otherwise you need to manually verify via the verifyOAuth method subsequently.
  • If no state parameter is provided, the system automatically generates a status parameter in prd-{provider}-{random string} format -The callback URL needs to be configured in the protected domains of the Cloud Development Platform, otherwise it will return a permission error.

参数

params
SignInWithOAuthReq

返回

Promise
SignInOAuthRes

示例

// 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, // Optional: automatically detect OAuth parameters in the URL
},
});

const { data, error } = await auth.signInWithOAuth({
provider: "wechat",
options: {
redirectTo: "https://example.com/callback",
state: "wx_auth_123456",
},
});

if (error) {
console.error("Failed to get Weixin authorization link:", error.message);
} else {
console.log("WeChat authorization link:", data.url);
console.log("third-party platform:", data.provider);
// Navigate to the WeChat authorization page
window.location.href = data.url;
}

signInWithIdToken

async signInWithIdToken(params: SignInWithIdTokenReq): Promise<SignInRes>

Log in with a third-party platform identity token, supporting mainstream platforms such as WeChat and Google.

-Log in with a third-party platform identity token, such as WeChat and Google. -Support specifying third-party platform identification. Third-party platforms must be configured in Cloud Development Platform/Identity Verification/Login Methods first. -Token is a required parameter

参数

params
SignInWithIdTokenReq

返回

Promise
SignInRes

示例

const { data, error } = await auth.signInWithIdToken({
provider: "wechat",
token: "wx_token_1234567890",
});

if (error) {
console.error("WeChat login failed:", error.message);
} else {
console.log("WeChat login successful, user information:", data.user);
console.log("session information:", data.session);
}

signInWithCustomTicket

async signInWithCustomTicket(getTickFn: GetCustomSignTicketFn): Promise<SignInRes>

Use custom login invoice to log in, support complete custom login process.

-Use custom login ticket to authenticate -Support passing functions to obtain custom login invoice

  • Suitable for scenarios requiring a complete custom login process
  • For the detailed process of issuing a Ticket, see Custom Login

参数

getTickFn
GetCustomSignTicketFn

Function to get custom login invoice, return Promise<string>

返回

Promise
SignInRes

示例

// Function to get custom login invoice
const getTickFn = () => Promise.resolve("custom_ticket_123456");

const { data, error } = await auth.signInWithCustomTicket(getTickFn);

if (error) {
console.error("Custom login failed:", error.message);
} else {
console.log("Custom login successful, user information:", data.user);
console.log("session information:", data.session);
}

signInWithOpenId

async signInWithOpenId(params?: SignInWithOpenIdReq): Promise<SignInRes>

WeChat mini program OpenID silent login. 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).

Note

Only supported for use in WeChat mini program

参数

params
SignInWithOpenIdReq

Login parameters

返回

Promise
SignInRes

示例

const { data, error } = await auth.signInWithOpenId();

signInWithPhoneAuth

async signInWithPhoneAuth(params: SignInWithPhoneAuthReq): Promise<SignInRes>

WeChat mini program mobile phone authorization login. 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).

Note

Only supported for use in WeChat mini program

参数

params
SignInWithPhoneAuthReq

Login parameters

返回

Promise
SignInRes

示例

const { data, error } = await auth.signInWithPhoneAuth({ phoneCode: "xxx" });

Session Management

getSession

async getSession(): Promise<SignInRes>

Retrieve current session info and check user login status.

-Retrieve current user session information, including access token and user information. -Check whether the user is logged in. Returns an empty session if not logged in

参数

无参数

返回

Promise
SignInRes

示例

const { data, error } = await auth.getSession();

if (error) {
console.error("Failed to get conversation:", error.message);
} else if (data.session) {
console.log("user logged in:", data.session.user);
console.log("Access token:", data.session.access_token);
console.log("Expiration time:", data.session.expires_in, "seconds");
} else {
console.log("user not logged in, please log in first");
Display the login button
document.getElementById("loginBtn").style.display = "block";
}

refreshSession

async refreshSession(refresh_token?: string): Promise<SignInRes>

Refresh the session token, extend 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 tokens or default tokens

参数

refresh_token
string

返回

Promise
SignInRes

示例

const { data, error } = await auth.refreshSession();

if (error) {
console.error("Refresh session fails:", error.message);
// Refresh fails, may need to log in again
window.location.href = "/login";
} else {
console.log(
"Session refreshed successfully, new token:",
data.session?.access_token
);
console.log("New expiration time:", data.session?.expires_in, "seconds");
}

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. -Session set successfully triggers SIGNED_IN event

参数

params
SetSessionReq

返回

Promise
SignInRes

示例

const { data, error } = await auth.setSession({
access_token: "your_access_token_here",
refresh_token: "your_refresh_token_here",
});

if (error) {
console.error("Failed to set session:", error.message);
} else {
console.log("Session set successfully");
console.log("user information:", data.user);
console.log("session information:", data.session);
}

signOut

async signOut(params?: SignOutReq): Promise<SignOutRes>

User logout, clear the current session and local storage.

-Log out current user login status securely -Clear server-side session and local storage -Support redirect to specified page

  • Trigger authentication status change event

参数

params
SignOutReq

返回

Promise
SignOutRes

示例

const { data, error } = await auth.signOut();

if (error) {
console.error("Logout failed:", error.message);
} else {
console.log("Logout successful");
Navigate to the login page after logging out
window.location.href = "/login";
}

User Management

getUser

async getUser(): Promise<GetUserRes>

Obtain currently logged in user detailed information, include identity information, metadata and permission status, support user profile show and permission 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 checking user permissions and verification status

参数

无参数

返回

Promise
GetUserRes

示例

const { data, error } = await auth.getUser();

if (error) {
console.error("Failed to obtain user information:", error.message);
} else if (data.user) {
const user = data.user;
console.log("uid:", user.ID);
console.log("mailbox:", user.email);
console.log("phone number:", user.phone);
console.log("userName:", user.user_metadata?.username);
console.log("nickName:", user.user_metadata?.nickName);
console.log("avatar:", user.user_metadata?.avatarUrl);
console.log("registration time:", user.created_at);
} else {
console.log("user not logged in");
}

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 is unsynced User must be logged in to refresh info

参数

无参数

返回

Promise
CommonRes

示例

const { data, error } = await auth.refreshUser();

if (error) {
console.error("Failed to update user information:", error.message);
} else {
console.log("user information refreshed");
console.log("latest user information:", data.user);
console.log("latest session information:", data.session);
}

updateUser

async updateUser(params: UpdateUserReq): Promise<GetUserRes>

Update current logged-in user info.

-Password update 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. -Users are advised to be logged in to update information Return upon success after update user information

参数

params
UpdateUserReq

返回

Promise
GetUserRes

示例

const { data, error } = await auth.updateUser({
nickname: "new nickname",
gender: "MALE",
});

if (error) {
console.error("Failed to update user information:", error.message);
} else {
console.log("user information updated:", data.user);
console.log("new email:", data.user?.email);
console.log("new nickname:", data.user?.user_metadata?.nickName);
}

deleteUser

async deleteUser(params: DeleteMeReq): Promise<CommonRes>

Delete the current logged-in user account.

-Permanently delete the current logged-in user account. -Verify user password to confirm identity -Once deleted, all user data will be permanently removed. -Irreversible operation. Use with caution.

参数

params
DeleteMeReq

返回

Promise
CommonRes

示例

const { data, error } = await auth.deleteUser({
password: "userPassword123",
});

if (error) {
console.error("Account deletion failed:", error.message);
} else {
console.log("Account deletion successful");
// User logged out, redirect to homepage
window.location.href = "/";
}

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/Login Methods. -Return the detailed information of the identity source, including platform identifier, identity source ID, binding time.

  • Users must be logged in to retrieve identity source information.

参数

无参数

返回

Promise
GetUserIdentitiesRes

示例

const { data, error } = await auth.getUserIdentities();

if (error) {
console.error("Failed to retrieve identity source:", error.message);
} else if (data.identities) {
console.log("user binding identity source:", data.identities);

data.identities.forEach((identity) => {
console.log(
`- ${identity.name} (${identity.provider}): ${identity.provider_user_id}`
);
console.log(
` Binding time: ${new Date(identity.created_at).toLocaleString()}`
);
});
} else {
console.log("user not bound to any identity source");
}

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 parties such as WeChat, Google, and GitHub. The identity source needs to be configured in Cloud Development Platform/Identity Verification/Login Methods first. -Binding succeeded. Users can use this identity source to log in.
  • User must be logged in to bind an identity source.
  • When setting auth.detectSessionInUrl to true in cloudbase.init, it will automatically call verifyOAuth to verify after returning from a third-party callback, otherwise you need to manually verify via the verifyOAuth method subsequently.

参数

params
LinkIdentityReq

返回

Promise
LinkIdentityRes

示例

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, // Optional: automatically detect OAuth parameters in the URL
},
});

// Listen to identity source bind event
auth.onAuthStateChange((event, session, info) => {
console.log("certification status transition:", { event, session, info });

switch (event) {
case "BIND_IDENTITY":
if (!!info.error) {
console.error("Failed to bind identity source:", info.error);
// Here add UI error prompt
} else {
console.log("identity source bound");
// Reload the identity source list
await auth.getUserIdentities();
}
break;

default:
return;
}
});

try {
const { data, error } = await auth.linkIdentity({
provider: "google",
});

if (error) {
console.error("Failed to bind identity source:", error.message);
// Handle binding failed logic
return;
}

console.log("identity source binding request sent, wait for user authorization...");
Binding request successful, wait for user to complete OAuth 2.0 authorization process
} catch (error) {
console.error("error occurs when calling linkIdentity method:", error);
Handle network error or other exceptions
}

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/Login 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.

参数

params
UnlinkIdentityReq

返回

Promise
CommonRes

示例

const { data, error } = await auth.unlinkIdentity({
provider: "wechat",
});

if (error) {
console.error("Failed to unbind identity source:", error.message);
} else {
console.log("identity source unbinding succeeded");

// Reload the identity source list
await auth.getUserIdentities();
}

Password Management

resetPasswordForEmail

async resetPasswordForEmail(email: string): Promise<ResetPasswordForEmailRes>

Resetting user password via mailbox, using a four-step verification process.

-Sending Captcha 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. -User email must be registered and verified.

参数

email
string

Email address for user registration

返回

Promise
ResetPasswordForEmailRes

示例

// Step 1: Send verification to mailbox
const { data, error } = await auth.resetPasswordForEmail("user@example.com");

if (error) {
console.error("Send Captcha failed:", error.message);
} else {
console.log("verification code sent to email, waiting for user input...");

Step 2: Wait for the user to input the Captcha and new password.
const verificationCode = "123456"; // user input
const newPassword = "newSecurePassword123"; // new password entered by user

// Step 3: Verify the verification code and set new password
const { data: loginData, error: loginError } = await data.updateUser({
nonce: verificationCode,
password: newPassword,
});

if (loginError) {
console.error("Password resetting failed:", loginError.message);
} else {
console.log("Password reset successful, user auto login");
console.log("user information:", loginData.user);
}
}

resetPasswordForOld

async resetPasswordForOld(params: ResetPasswordForOldReq): Promise<SignInRes>

Reset the password of the current logged-in user using the old password.

-Reset the password of the current logged-in user by verifying the old password. -Users are advised to be logged in -Suitable for scenarios where users remember the old password

参数

params
ResetPasswordForOldReq

返回

Promise
SignInRes

示例

const { data, error } = await auth.resetPasswordForOld({
new_password: "newSecurePassword123",
old_password: "oldPassword123",
});

if (error) {
console.error("Password reset failed:", error.message);
} else {
console.log("password reset successful");
console.log("user information:", data.user);
console.log("session information:", data.session);
}

reauthenticate

async reauthenticate(): Promise<ReauthenticateRes>

Re-authenticate the current logged-in user identity through verification code verification and allow the modification of the password.

Note

SMS verification code is only supported in the Shanghai region

-Re-authenticate the present logged-in user identity and support update password. -Verify by sending a verification code to the user's registered mailbox or mobile number, giving priority to the mailbox. If the mailbox is not set by the user, use the mobile number. -Applicable to identity verification before security-sensitive operations

参数

无参数

返回

Promise
ReauthenticateRes

示例

// Step 1: Send Captcha (use current user info)
const { data, error } = await auth.reauthenticate();

if (error) {
console.error("Send Captcha failed:", error.message);
} else {
console.log("verification code sent, waiting for user input...");

Step 2: Wait for the user to input the Captcha and new password.
const verificationCode = "123456"; // user input
const newPassword = "newSecurePassword123"; // new password entered by user

// Step 3: Verify the verification code and set new password
const { data: loginData, error: loginError } = await data.updateUser({
nonce: verificationCode,
password: newPassword,
});

if (loginError) {
console.error("Authentication fail again:", loginError.message);
} else {
console.log("Authentication succeeded again, password updated");
console.log("user information:", loginData.user);
}
}

Verification Management

verifyOAuth

async verifyOAuth(params?: VerifyOAuthReq): Promise<SignInRes>

Verify third-party platform authorization callback and complete the OAuth login process.

-Verify third-party platform authorization callback, retrieve user information and complete login, can be used in conjunction with signInWithOAuth

  • Support automatically obtaining authorization code and status parameter from URL parameter -Provide complete security verification mechanism to prevent CSRF attack

参数

params
VerifyOAuthReq

返回

Promise
SignInRes

示例

// Call on the callback page to automatically obtain URL parameters
const { data, error } = await auth.verifyOAuth();

if (error) {
console.error("Authorization verification failed:", error.message);
} else {
console.log("Authorization successful, user information:", data.user);
console.log("session information:", data.session);

Navigate to the homepage after successful verification
window.location.href = "/home";
}

verifyOtp

async verifyOtp(params: VerifyOtpReq): Promise<SignInRes>

Verify the one-time password (OTP) to complete login or sign-up process.

Note

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).

  • After successful verification, automatically log in the user and return session information
  • Suitable for registration, login, password reset, and other scenarios

参数

params
VerifyOtpReq

返回

Promise
SignInRes

示例

const phone = "13800138000";

// Get a Captcha
const { data } = await auth.resend({ phone });

// 2. Verify the Captcha
const { data: verifyData, error } = await auth.verifyOtp({
phone: "13800138000",
token: "123456",
messageId: data.messageId,
});

if (error) {
console.error("Verification failed:", error.message);
} else {
console.log("Verification successful, user information:", data: verifyData.user);
console.log("session information:", data: verifyData.session);
}

resend

async resend(params: ResendReq): Promise<ResendRes>

Resend Captcha to mailbox or mobile number.

Note

SMS verification code is only supported in the Shanghai region

-Resend Captcha to user's mailbox or mobile number -Support registration, mailbox update, mobile number update, and other scenarios -Resend to get a new message ID for the verification process -Provide rate limit protection to prevent malicious resend

参数

params
ResendReq

返回

Promise
ResendRes

示例

// Send a Captcha for the first time
const { data, error } = await auth.signInWithOtp({ phone: "13800138000" });

// Captcha verification callback
let signUpVerify = data.verifyOtp;

// Resend the verification code to get a new messageId
const { data: resendData, error: resendError } = await auth.resend({
phone: "13800138000",
type: "signup",
});

if (resendError) {
console.error("Resend verification code failed:", resendError.message);
console.error("error code:", resendError.code);
} else {
console.log("Verification code resent, message ID:", resendData.messageId);

Pass the new messageId to the back parameter of signInWithOtp() or signUp()
const verificationCode = "123456"; // user input
const messageId = resendData.messageId; // new messageId

// Use the new messageId to verify
const { data: loginData, error: loginError } = await signUpVerify({
token: verificationCode,
messageId,
});

if (loginError) {
console.error("Verification failed:", loginError.message);
} else {
console.log("Verification successful");
}

// Start countdown
startCountdown(60);
}

Other tools

onAuthStateChange

onAuthStateChange(callback: OnAuthStateChangeCallback): OnAuthStateChangeResult

Listen for authentication status changes and respond to events such as login, logout, and token refresh in real time.

  • Listen for user authentication status change events -Support various event types: login, logout, token refresh, user information update, identity source bind. -Return the subscription object for cancel listening -Suitable to build responsive UI and status management

参数

callback
OnAuthStateChangeCallback

callback function for state changes

返回

OnAuthStateChangeResult
object

示例

const { data } = auth.onAuthStateChange((event, session, info) => {
console.log("certification status transition:", event, session, info);

switch (event) {
case "INITIAL_SESSION":
console.log("initial session established");
if (session) {
console.log("user logged in:", session.user?.email);
} else {
console.log("user not logged in");
}
break;

case "SIGNED_IN":
console.log("user login successful:", session.user?.email);
// Update UI display
document.getElementById("loginBtn").style.display = "none";
document.getElementById("userInfo").style.display = "block";
document.getElementById("userEmail").innerText =
session.user?.email || "";
break;

case "SIGNED_OUT":
console.log("user logged out");
// Update UI display
document.getElementById("loginBtn").style.display = "block";
document.getElementById("userInfo").style.display = "none";
break;

case "PASSWORD_RECOVERY":
console.log("password reset");
Show password reset interface
document.getElementById("passwordResetForm").style.display = "block";
break;

case "TOKEN_REFRESHED":
console.log("Token refreshed");
break;

case "USER_UPDATED":
console.log("user information updated");
// Update user information display
if (session) {
document.getElementById("userEmail").innerText =
session.user?.email || "";
document.getElementById("userAvatar").src =
session.user?.user_metadata?.avatarUrl || "";
}
break;

case "BIND_IDENTITY":
console.log("identity source binding result");
if (!!info.error) {
console.log("identity source binding failed");
} else {
console.log("identity source bound");
}
break;
}
});

// Cancel listening (called during component uninstallation)
// data.subscription.unsubscribe();

getClaims

async getClaims(): Promise<GetClaimsRes>

Retrieve the claim info from the current access token for debug and permission check.

-Parse the JWT claim info in the current access token -Return the header, claim, and signature of the token. -For debug token info, check permissions and verify token status. -Users are advised to be logged in to obtain token info

参数

无参数

返回

Promise
GetClaimsRes

示例

const { data, error } = await auth.getClaims();

if (error) {
console.error("Failed to retrieve declaration:", error.message);
} else {
console.log("Token claim info:", data.claims);
console.log("Token header information:", data.header);
console.log("Token signature:", data.signature);

// Parse user information
if (data.claims) {
console.log("User ID:", data.claims.sub);
console.log(
"Expiration time:",
new Date(data.claims.exp * 1000).toLocaleString()
);
console.log(
"Issuance time:",
new Date(data.claims.iat * 1000).toLocaleString()
);
console.log("user role:", data.claims.role);
}
}

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 carrying custom parameters and redirect
Local debugging

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 Whistle proxy Rules configuration is as follows:

https://lowcode-xxx-xxx.tcloudbaseapp.com http://localhost:3000

# Configure proxy for other application paths

After running the application, you can access it at https://lowcode-xxx-xxx.tcloudbaseapp.com.

参数

params
ToDefaultLoginPageReq

返回

Promise
CommonRes

示例

const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});

const auth = app.auth();

await auth.toDefaultLoginPage({
config_version: "env",
app_id: "app-xxx",
redirect_uri: "xxx",
});

Error Code

Login error

Error CodeDescription
not_foundUser does not exist
password_not_setThe current user has not set a password. Please use Captcha or third-party login method
invalid_passwordIncorrect Password
user_pendingUser not activated
user_blockedUser disabled
invalid_statusYou have exceeded the maximum number of retries for password, please retry later
invalid_two_factorMFA code mismatched or outdated

Registration error

Error CodeDescription
failed_preconditionThe mobile number or mailbox you input has been registered, please use another number
Error CodeDescription
failed_preconditionFailed to obtain user information from third party
resource_exhaustedAttempt too frequent, try again later
invalid_argumentThe input Captcha is incorrect or expired
abortedToo many attempts, back to homepage and try again later
permission_deniedYour current session expired, back and retry
captcha_requiredNeed to enter Captcha, based on anti-robot service access
captcha_invalidIncorrect Captcha, based on anti-robot service access

Other Errors

Error CodeDescription
unreachableNetwork error, check your network connection and try again later

Error Description

Error CodeError DescriptionDescription
permission_deniedcors permission denied, please check if {url} is in your client {env} domainsplease check whether the secure domain name {url} is already configured for the {env} environment in "cloud Development Platform/Environment Configuration/Secure source/Protected domains" (https://tcb.cloud.tencent.com/dev?envId=#/env/safety-source). It will take effect 10 minutes after configuration.

Complete type definition

SignInAnonymouslyReq

Anonymous login parameter
interface SignInAnonymouslyReq {
provider_token?: string; // Provider 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; // Anonymous or not
// 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
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: Mobile 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: Precondition 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: {}; // empty object on success
error: AuthError | null; // Error info. null on success
}

SignUpReq

// User registration parameters (four-step verification process)
interface SignUpReq {
email?: string; // Email address (optional, choose either this or mobile number)
phone?: string; // Mobile number (optional, choose either this or email address)
password: string; // Password (required)
username?: string; // Username (optional), length 5-24 characters, supports Chinese and English letters, numbers, 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 parameter
interface SignOutReq {
options?: {
// Configuration option (optional)
redirectTo?: string; // Redirection address after logout
clearStorage?: boolean; // Whether to clear local storage (default true)
};
}

SignInWithPasswordReq

// Password login parameter
interface SignInWithPasswordReq {
username?: string; // Username (optional, choose one among username, mailbox, or phone number), length 5-24 characters, supports Chinese and English letters, numbers, special characters (only _- allowed), Chinese characters are not allowed
email?: string; // Email address (optional, choose one among email address, username, or mobile number)
phone?: string; // Mobile number (optional, choose one among mobile number, username, or email address)
password: string; // Password (required)
is_encrypt?: boolean; // Encrypted or not; false by default
}

SignInWithIdTokenReq

// ID token login parameter
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 parameter
interface SignInWithOtpReq {
email?: string; // Email address (optional, choose either this or mobile number)
phone?: string; // Mobile number (optional, choose either this or email address)
}

SignInWithOAuthReq

// OAuth authorization parameter
interface SignInWithOAuthReq {
provider: string; // Third-party platform flag (required)
options?: {
// Configuration option (optional)
redirectTo?: string; // Callback URL, defaults to current page
skipBrowserRedirect?: boolean; // Whether to navigate to the authorization page, default false
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, which will be 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 parameter
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 parameter
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 mobile number)
phone?: string; // Mobile number (optional, choose either this or email address)
token: string; // Captcha (required)
messageId: string; // ID corresponding to the verification code (required)
}

UpdateUserReq

// User information update parameters
interface UpdateUserReq {
email?: string; // Email address
phone?: string; // Phone number
username?: string; // Username (optional), length 5-24 characters, supports Chinese and English letters, numbers, 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 info
}

ResendReq

// Resend verification code parameter
interface ResendReq {
email?: string; // Email address (optional, choose either this or mobile number)
phone?: string; // Mobile number (optional, choose either this or email address)
type?: "signup" | "email_change" | "phone_change" | "sms"; // Type (optional)
}

ResendRes

// Resend verification code response parameter
interface ResendRes {
data: {
messageId?: string; // Message ID (Captcha ID)
};
error: AuthError | null; // Error info. null on success
}

SignInWithOtpRes

// OTP login response parameter
interface SignInWithOtpRes {
data: {
verifyOtp?: (params: {
token: string;
messageId?: string;
}) => Promise<SignInRes>; // Captcha callback function, supports messageId parameter
};
error: AuthError | null; // Error info. null on success
}

SignUpRes

// User registration response parameter
interface SignUpRes {
data: {
verifyOtp?: (params: {
token: string;
messageId?: string;
}) => Promise<SignInRes>; // Captcha callback function, supports messageId parameter
};
error: AuthError | null;
}

SignInOAuthRes

// OAuth authorization response parameter
interface SignInOAuthRes {
data: {
url?: string; // Authorization page URL
provider?: string; // Third-party platform flag
scopes?: string; // Authorization scope
};
error: AuthError | null; // Error info. null on success
}

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 info. null on success
}

Identity

interface Identity {
id: string; // Identity source flag
name: string; // Identity source name
picture: string; // Avatar URL
}

GetUserIdentitiesRes

// 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 info. null on success
}

GetClaimsRes

// Declaration information acquisition response parameter
interface GetClaimsRes {
data: {
// token claim 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 info. null on success
}

ResetPasswordForOldReq

// Reset password parameter with old password
interface ResetPasswordForOldReq {
new_password: string; // New password (required)
old_password: string; // Old password (required)
}

DeleteMeReq

// Current user deletion parameter
interface DeleteMeReq {
password: string; // User password (required)
}

SignInRes

// Login response parameter
interface SignInRes {
data: {
user?: User; // User information
session?: Session; // Session information
};
error: AuthError | null; // Error info. null on success
}

GetUserRes

// User information retrieval response parameter
interface GetUserRes {
data: {
user?: User; // User details
};
error: AuthError | null; // Error info. null on success
}

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 info. null on success
}

UpdateUserAttributes

// User attribute update parameters
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 info. null on success
}