Authentication
Under the new login system, ensure that one environment corresponds to one tcb instance (avoid initializing tcb instances for the same environment multiple times).
App.auth()
Interface Description
Returns the Auth object. Authentication-related properties and methods are all contained within the Auth object.
Interface declaration: auth(): Auth
@cloudbase/js-sdk@2.x version will only support the local method for storing authentication state (on the Web side, the authentication state is retained for 30 days before explicit logout). (The session and none modes from the original 1.x version are no longer supported)
Sample Code
import cloudbase from "@cloudbase/js-sdk";
const app = cloudbase.init({
env: "xxxx-yyy",
clientId: "xxxx",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
Registration/Login/Logout Related
Phone number Captcha registration is only supported in the Shanghai region
Auth.signUp()
Interface Description
Interface feature: Register a user. Currently supports phone number verification code registration and email verification code registration.
Interface declaration: signUp(params: SignUpRequest): Promise<LoginState>
Input Parameters: SignUpRequest
| Field | Type | Required | Description |
|---|---|---|---|
| phone_number | string | No | The phone number used for registration. Either phone_number or email must be used. |
| string | No | The email used for registration. Either phone_number or email must be used. | |
| verification_code | string | No | The verification code, which can be obtained via Auth.getVerification |
| verification_token | string | No | The verification code token, which can be obtained via Auth.verify |
| provider_token | string | No | The third-party provider token, used to bind third-party user information, which can be obtained via Auth.grantProviderToken |
| password | string | No | Password |
| name | string | No | Username |
| gender | string | No | Gender |
| picture | string | No | Avatar |
| locale | string | No | Address |
Output Parameters: LoginState
See LoginState
Sample Code
// Initialize the SDK
const app = cloudbase.init({
env: "xxxx-yyy",
clientId: "xxxxx",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// Example: Phone number verification code registration
// Step 1: User clicks to obtain the verification code, calls the following method to send the SMS verification code, and stores verificationInfo globally for convenient parameter input in Step 3
const phoneNumber = "+86 13800000000";
const verification = await auth.getVerification({
phone_number: phoneNumber,
});
// If using email verification, change the code for the first step to
{
const email = "test@example.com";
const verification = await auth.getVerification({
email: email,
});
}
// Verify verification code
// After calling the SMS sending interface, the mobile phone will receive an SMS verification code from TCB.
// The user enters the SMS verification code and can call the following interface for verification.
// Step 2: Wait for the user to enter the SMS verification code on the page
const verificationCode = userInputCode; // 6-digit verification code
// Step 3: Verify the SMS verification code once the user has entered it
const verificationTokenRes = await auth.verify({
verification_id: verification.verification_id,
verification_code: verificationCode,
});
// Step 4: Register
// If the user already exists, log in
if (verification.is_user) {
await auth.signIn({
username: phoneNumber,
verification_token: verificationTokenRes.verification_token,
});
} else {
// Otherwise, register a new user and set a password and username.
// Remark: Upon successful signUp, the user will be automatically logged in.
await auth.signUp({
phone_number: phoneNumber,
verification_code: verificationCode,
verification_token: verificationTokenRes.verification_token,
// Optional, set nickname.
name: name: "Mobile User",
// Optional, set password.
password: "password",
// Optional, set login username.
username: "username",
});
}
Auth.signIn()
Phone number login is only supported in the Shanghai region
Interface Description
Interface feature: After registration is completed, users can log in using this method. Currently, it supports login via phone number, email, and username/password.
Interface declaration: signIn(params: SignInRequest): Promise<LoginState>
Input Parameters: SignInRequest
| Field | Type | Required | Description |
|---|---|---|---|
| username | string | Required | User's phone number, email, or custom username. If it is a Chinese phone number, include the country code "+86", for example, "+86 138xxxxxxxxx". |
| password | string | No | User password. Either password or verification_token must be provided. |
| verification_token | string | No | The verification code token. Either password or verification_token must be provided, which can be obtained via Auth.verify |
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
clientId: "xxxxx",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// Registration completed
// Example: Phone number login
const phoneNumber = "+86 13800000000";
await auth.signIn({
username: phoneNumber,
password: "your password",
});
// Example: Email login
const email = "test@example.com";
await auth.signIn({
username: email,
password: "your password",
});
// Example: Username login
const username = "myname";
await auth.signIn({
username,
password: "your password",
});
Auth.signOut()
Interface Description
Interface feature: Log out
Interface declaration: signOut(params?: SignoutRequest): Promise<SignoutReponse>
Input Parameters: SignoutRequest
| Field | Type | Required | Description |
|---|---|---|---|
| redirect_uri | string | No | Redirect URL after sign out |
| state | string | No | When redirect_uri is provided, this parameter will be passed as a parameter in the state field of the redirect_uri link to identify a specific identity source |
Output Parameters: SignoutReponse
| Field | Type | Description |
|---|---|---|
| redirect_uri | string | The redirect URL. This field is returned if redirect_uri is passed in the input parameters or configured in the third-party identity source. |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// Listen for login status changes
auth.onLoginStateChanged((params) => {
console.log(params);
const { eventType } = params?.data || {};
switch (eventType) {
case "sign_in":
// Login successful
break;
case "sign_out":
// Logout successful
break;
case "credentials_error":
// Permission invalid
break;
default:
return;
}
});
await auth.signOut();
Auth.signInAnonymously()
Interface Description
Interface feature: anonymous login
Interface declaration signInAnonymously(): Promise<LoginState>
Input Parameters: None
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
await auth.signInAnonymously();
Anonymous Login Upgrade Example
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
})
const auth = app.auth()
// 1. Anonymous login
await auth.signInAnonymously()
// 2. Obtain accesstoken
const access_token = await auth.getAccessToken()
// 3. Upgrade registration
await auth.signUp({
...// For parameter passing, refer to the Auth.signUp interface
anonymous_token: access_token
})
Auth.setCustomSignFunc()
Interface Description
Interface feature: Sets the function to obtain a custom login ticket
Interface declaration: setCustomSignFunc(getTickFn: GetCustomSignTicketFn): void
Parameters: GetCustomSignTicketFn
| Field | Type | Description |
|---|---|---|
| getTickFn | () => Promise<string> | Function to obtain a custom login ticket |
Output Parameters: None
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const getTickFn = new Promise((resolve, reject));
await auth.setCustomSignFunc(getTickFn);
Auth.signInWithCustomTicket()
Interface Description
Interface feature: Custom login, used in conjunction with Auth.setCustomSignFunc
Interface declaration: signInWithCustomTicket(): Promise<LoginState>
Input Parameters: None
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
await auth.signInWithCustomTicket();
Auth.signInWithOpenId()
is only supported in the WeChat Mini Program region
Interface Description
Interface feature: 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 TCB - Login Methods.
Interface declaration: signInWithOpenId(params?: SignInWithOpenIdReq): Promise<LoginState>
Input Parameters: SignInWithOpenIdReq
| Field | Type | Required | Default Value | Description |
|---|---|---|---|---|
| useWxCloud | boolean | No | true | true: Use WeChat Cloud Development mode for requests, requires enabling the Mini Program WeChat Cloud Development environment; false: Use regular http requests |
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
await auth.signInWithOpenId();
Auth.signInWithUnionId()
is only supported in the WeChat Mini Program region
Interface Description
Interface feature: WeChat Mini Program unionId 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 TCB - Login Methods.
Interface declaration: signInWithUnionId(): Promise<LoginState>
Input Parameters: None
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
await auth.signInWithUnionId();
Auth.signInWithPhoneAuth()
is only supported in the WeChat Mini Program region
Interface Description
Interface feature: WeChat Mini Program phone number authorized 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 TCB - Login Methods.
Interface declaration: signInWithPhoneAuth(params: SignInWithPhoneAuthReq): Promise<LoginState>
Input Parameters: SignInWithPhoneAuthReq
| Field | Type | Required | Default Value | Description |
|---|---|---|---|---|
| phoneCode | string | Yes | Empty | WeChat Mini Program phone number authorization code, obtained via the WeChat Mini Program Phone Number Quick Verification Component |
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
await auth.signInWithPhoneAuth({ phoneCode: "xxx" });
Auth.signInWithSms()
is only supported in the Shanghai region
Interface Description
Interface feature: SMS verification code login
Interface declaration: signInWithSms(params: SignInWithSmsReq): Promise<LoginState>
Input Parameters: SignInWithSmsReq
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| verificationInfo | object | Verification token information | {} | Return value of Auth.getVerification |
| verificationCode | string | Verification code | empty | The obtained SMS verification code will be sent after calling Auth.getVerification |
| phoneNum | string | Phone number | empty | The phone number for obtaining the verification code. Chinese phone numbers must include the country code "+86", e.g., "+86 138xxxxxxxxx" |
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const phoneNumber = "+86 13800000000";
// Step 1: User clicks to obtain the verification code, calls the following method to send the SMS verification code, and stores verificationInfo globally for convenient parameter input in Step 3
const verificationInfo = await auth.getVerification({
phone_number: phoneNumber,
});
// Step 2: Wait for the user to enter the SMS verification code on the page
const verificationCode = userInputCode; // 6-digit verification code
// Step 3: Verify the SMS verification code and log in once the user has entered it
await auth.signInWithSms({
verificationInfo,
verificationCode, // SMS verification code entered by the user
phoneNum: phoneNum: phoneNumber, // User's phone number
});
Auth.signInWithEmail()
Interface Description
Interface feature: Email verification code login
Interface declaration: signInWithEmail(params: SignInWithEmailReq): Promise<LoginState>
Input Parameters: SignInWithEmailReq
| Field | Type | Required | Default | Description |
|---|---|---|---|---|
| verificationInfo | object | Verification token information | {} | Return value of Auth.getVerification |
| verificationCode | string | Verification code | empty | Obtained email verification code, which will be sent after calling Auth.getVerification |
| string | empty | Email address for obtaining the verification code |
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const email = "test@example.com";
// Step 1: User clicks to obtain the verification code, call the following method to send the email verification code, store verificationInfo globally for convenient parameter input in Step 3.
const verificationInfo = await auth.getVerification({
email: email,
});
// Step 2: Wait for the user to enter the email verification code on the page
const verificationCode = userInputCode; // 6-digit verification code
// Step 3: After the user has entered the verification code, verify the email verification code and log in.
await auth.signInWithEmail({
verificationInfo,
verificationCode, // User-entered email verification code
email: email: email, // User email
});
Auth.toDefaultLoginPage()
To use this feature, please upgrade @cloudbase/js-sdk to version 2.18.0 or later.
Interface Description
Interface feature: Redirect to the system default login page, compatible with web and WeChat Mini Program.
Interface declaration: toDefaultLoginPage(params: authModels.ToDefaultLoginPage): Promise<void>
Input Parameters: ToDefaultLoginPage
| Field | Type | Meaning | Default Value | Description |
|---|---|---|---|---|
| config_version | string | Login configuration version for the default login page | env | 1. 'env' indicates the hosted login page configuration, which can be set in "TCB - Authentication". 2. Non-'env' values indicate the use of an independent hosted login page configuration, which can be set in "TCB - Visual Low Code - Access Control". The corresponding config_version can be obtained from the parameters in the link of the application's automatically redirected __auth login page. |
| redirect_uri | string | Redirect URL after login | Defaults to the current page URL | |
| app_id | string | Application id | Empty | Required when config_version is not 'env', e.g., app-xxx |
| query | object | Parameters to be carried when redirecting to the default login page | Empty |
Output Parameters: None
Sample Code
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",
});
Third-party Platform Login Related
Auth.genProviderRedirectUri()
Interface Description
Interface feature: Generate authorization Uri for third-party platforms (e.g., WeChat QR code scan authorization webpage)
Interface declaration: genProviderRedirectUri(params: GenProviderRedirectUriRequest): Promise<GenProviderRedirectUriResponse>
Input Parameters: GenProviderRedirectUriRequest
| Field | Type | Required | Description |
|---|---|---|---|
| provider_id | string | Yes | Third-party platform ID, refer to the built-in third-party platforms list |
| provider_redirect_uri | string | Yes | Third-party platform redirect Uri. After authorization is completed, the redirect url will carry a code parameter. |
| state | string | Yes | User-defined state identifier field to identify the source of third-party platform callbacks |
| other_params | {sign_out_uri?:string} | No | Other parameters |
Output Parameters: GenProviderRedirectUriResponse
| Field | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | Client request |
| signout_uri | string | Yes | Sign-out Uri |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const providerId = "test_provider_id"; // Third-party platform ID
const providerUri = "test_provider_redirect_uri"; // Third-party platform redirect Uri
const state = "wx_open"; // User-defined state identifier field
const otherParams = { sign_out_uri: "test_sign_out_uri" }; // Other parameters
// Sample for authorized login via third-party platform
// 1. Obtain the authorization page address for third-party platforms (e.g., WeChat authorization)
const { uri } = await auth.genProviderRedirectUri({
provider_id: providerId,
provider_redirect_uri: providerUri,
state: state,
other_params: otherParams,
});
// 2. Access the uri (e.g., location.href = uri)
// 3. Authorize (e.g., WeChat scan code authorization)
// 4. Callback to the provider_redirect_uri address (the url query carries authorization code, state, and other parameters), at this point check whether the state matches the expected value (such as the self-set wx_open).
const provider_code = "your provider code";
// 5. If the state matches the expected value (e.g., WeChat Open Platform authorization wx_open), then obtain the third-party platform token
const { provider_token } = await auth.grantProviderToken({
provider_id: "wx_open",
provider_redirect_uri: provider_redirect_uri: "cur page", // Specify the redirect url for the third-party platform
provider_code: provider_code: provider_code, // The code parameter carried in the url param when redirecting back to the page from a third-party platform
});
// 6. Only login or login and register via provider_token (related to the TCB platform - login method - identity source login mode configuration)
await auth.signInWithProvider({
provider_token,
});
Auth.grantProviderToken()
Interface Description
Interface feature: Provides third-party platform login token
Interface declaration: grantProviderToken(params: GrantProviderTokenRequest): Promise<GrantProviderTokenResponse>
Input Parameters: GrantProviderTokenRequest
| Field | Type | Required | Description |
|---|---|---|---|
| provider_id | string | Yes | Third-party platform ID, refer to the built-in third-party list |
| provider_redirect_uri | string | No | redirect uri for third-party platform |
| provider_code | string | No | Third-party platform authorization code (carried in the redirect uri) |
| provider_access_token | string | No | Third-party platform access token (carried in the redirect uri) |
| provider_id_token | string | No | Third-party platform ID token (carried in the redirect uri) |
Output Parameters: GrantProviderTokenResponse
| Field | Type | Required | Description |
|---|---|---|---|
| provider_token | string | Yes | Third-party platform token |
| expires_in | number | Yes | Validity period |
| provider_profile | ProviderProfile | No | Third-party identity source information |
ProviderProfile
| Field | Type | Required | Description |
|---|---|---|---|
| provider_id | string | Yes | Default built-in third-party provider IDs: wx_open, wx_mp |
| sub | string | Yes | Third-party user id (e.g. wxopenid) |
| name | string | No | Name |
| phone_number | string | No | Phone number |
| picture | string | No | Avatar |
| meta | ProviderProfileMeta | No | Extended information of third-party identity source (returned by mini-program) |
ProviderProfileMeta
| Field | Type | Required | Description |
|---|---|---|---|
| appid | string | No | The mini-program's appid |
| openid | string | No | The mini-program's openid |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const providerId = "wx_open"; // WeChat Open Platform
auth.grantProviderToken({
provider_id: providerId,
provider_redirect_uri: provider_redirect_uri: "cur page", // Specify the redirect url for the third-party platform
provider_code: provider_code: "provider code", // The code parameter carried in the url parameters when redirecting back to the page from a third-party platform
});
Auth.signInWithProvider()
Interface Description
Interface feature: Third-party platform 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 TCB - Login Methods.
Interface declaration: signInWithProvider(params: SignInWithProviderRequest): Promise<LoginState>
Input Parameters: SignInWithProviderRequest
| Field | Type | Required | Description |
|---|---|---|---|
| provider_token | string | Yes | Third-party platform token, which can be obtained via Auth.grantProviderToken |
Output Parameters: LoginState
See LoginState
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const providerToken = "test_provider_token";
auth.signInWithProvider({
provider_token: providerToken,
});
Auth.unbindProvider()
Interface Description
Interface feature: Unbind third-party accounts
Interface declaration: unbindProvider(params: UnbindProviderRequest): Promise<void>
Input Parameters: UnbindProviderRequest
| Field | Type | Required | Description |
|---|---|---|---|
| provider_id | string | Yes | Third-party platform ID, refer to the returned value during third-party binding, which can be obtained via Auth.getProviders |
Output Parameters: None
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// After login
// Obtain the bound third-party platform ID
const { id } = await auth.getProviders();
await auth.unbindProvider({
provider_id: id,
});
Auth.getProviders()
Interface Description
Interface feature: Obtain third-party binding list
Interface declaration: getProviders(): Promise<UserProfileProvider>
Input Parameters: None
Output Parameters: UserProfileProvider
| Field | Type | Required | Description |
|---|---|---|---|
| id | string | Yes | Third-party platform ID |
| provider_user_id | string | Yes | Third-party platform user ID |
| name | string | Yes | Third-party platform nickname |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// After login
await auth.getProviders();
Auth.bindWithProvider()
Interface Description
Interface feature: Bind third-party login
Interface declaration: bindWithProvider(params: BindWithProviderRequest): Promise<void>
Input Parameters: BindWithProviderRequest
| Field | Type | Required | Description |
|---|---|---|---|
| provider_token | string | Yes | Third-party platform authorization token, which can be obtained via Auth.grantProviderToken |
Output Parameters: None
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const provider_token = "test_provider_token"; // Refer to Auth.grantProviderToken to obtain
const auth = app.auth();
await auth.bindWithProvider({
provider_token,
});
Authentication/Authorization Related
Auth.verify()
"SMS verification code only supports the Shanghai region."
Interface Description
Interface feature: Verification code authentication, including SMS verification codes and email verification codes.
Interface declaration: verify(params: VerifyRequest): Promise<VerifyResponse>
Input Parameters: VerifyRequest
| Field | Type | Required | Description |
|---|---|---|---|
| verification_code | string | Yes | The verification code, which can be obtained via Auth.getVerification |
| verification_id | string | Yes | The verification code ID, which can be obtained via Auth.getVerification |
Output Parameters: VerifyResponse
| Field | Type | Required | Description |
|---|---|---|---|
| verification_token | string | No | Verification code token |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// Example: Phone number verification code / email verification code registration
// Step 1: User clicks to obtain the verification code, calls the following method to send the SMS verification code, and stores verificationInfo globally for convenient parameter input in Step 3
const phoneNumber = "+86 13800000000";
const verificationInfo = await auth.getVerification({
phone_number: phoneNumber,
});
/*
// If using email verification, change the code for the first step to
const email = "test@example.com"
const verificationInfo = await auth.getVerification({
email: email
});
*/
// Step 2: Wait for the user to enter the verification code on the page
const verificationCode = userInputCode; // 6-digit verification code
// Step 3: Verify the verification code once the user has entered it
await auth.verify({
verification_code: verificationCode,
verification_id: verificationInfo.verification_id,
});
Auth.getVerification()
Obtain SMS verification code only supports the Shanghai region.
Interface Description
Interface feature: Obtain SMS/email verification codes
Interface declaration: getVerification(params: GetVerificationRequest): Promise<GetVerificationResponse>
Input Parameters: GetVerificationRequest
| Field | Type | Required | Description |
|---|---|---|---|
| phone_number | string | No | Phone number. For Chinese phone numbers, the country code "+86 " must be included, e.g., "+86 138xxxxxxxxx". Either phone_number or email must be used. |
| string | No | Email address. Either email or phone_number must be used. | |
| target | Target | No | The application scenario for phone number or email. |
Target
| Value | Meaning |
|---|---|
| ANY | Does not verify the existence of the phone number or email. Use case: registration or login scenarios without an existing login state. |
| USER | The phone number or email must exist in the system and be bound to a user. |
Output Parameters: GetVerificationResponse
| Field | Type | Description |
|---|---|---|
| verification_id | string | Verification code id |
| is_user | boolean | Whether the user is registered |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const verificationCode = "000000";
const phoneNumber = "+86 13800000000";
// const email = "test@example.com";
const verification = await auth.getVerification({
phone_number: phoneNumber,
// email: email,
});
Auth.sudo()
Interface Description
Interface feature: Obtain advanced operation permissions through the sudo interface, such as changing passwords (Auth.setPassword), changing phone numbers (Auth.bindPhoneNumber), changing emails (Auth.bindEmail), deleting users (Auth.deleteMe), etc.
Interface declaration: Auth.sudo(params: SudoRequest): Promise<SudoResponse>
Input Parameters: SudoRequest
| Field | Type | Required | Description |
|---|---|---|---|
| password | string | No | Password. Either password or verification_token must be chosen. If a phone number is bound, then verification_token must be used for sudo. |
| verification_token | string | No | token obtained by verifying the bound phone number or email, which can be acquired via Auth.verify |
Output Parameters: SudoResponse
| Field | Type | Description |
|---|---|---|
| sudo_token | string | Elevated privilege token. If the user has only enabled third-party login and has not set a password, the sudo token will be an empty string "" |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// Method 1: Using password
const pass = "test_password";
const sudoRes = await auth.sudo({
password: pass,
});
console.log(sudoRes.sudo_token);
// Method 2: Obtain via email verification code or phone verification code.
// The email address or phone number bound to the current account
const email = "test@example.com";
// const phoneNumber = "+86 13800000000"
// Step 1: User clicks to obtain the verification code, calls the following method to send the verification code, and stores verificationInfo globally for convenient parameter input in Step 3
const verificationInfo = await auth.getVerification({
email: email,
// phone_number: phoneNumber
});
// Step 2: Wait for the user to enter the verification code on the page
const verificationCode = userInputCode; // 6-digit verification code
// Step 3: Verify the verification code once the user has entered it
const verificationTokenRes = await auth.verify({
verification_id: verificationInfo.verification_id,
verification_code: verificationCode,
});
// Step 4: Obtain sudo_token
const sudoRes = await auth.sudo({
verification_token: verificationTokenRes.verification_token,
});
console.log(sudoRes.sudo_token);
// Methods such as auth.setPassword, auth.bindEmail, auth.bindPhoneNumber, auth.deleteMe can be called
Auth.getAccessToken()
Interface Description
Interface feature: Obtain access token accessToken
Interface declaration: Auth.getAccessToken(): Promise<GetAccessTokenResponse>
Input Parameters: None
Output Parameters: GetAccessTokenResponse
| Field | Type | Description |
|---|---|---|
| accessToken | string | Access token |
| env | string | Environment id |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// After logging in via some method...
// Obtain access_token
const { accessToken } = await auth.getAccessToken();
console.log(accessToken);
User Information Related
Auth.getCurrentUser()
Interface Description
Interface feature: Asynchronous operation of Auth.currentUser, returns a User instance representing the current user
Interface declaration: getCurrentUser(): Promise<User | null>
Input Parameters: None
Output Parameters: User
See User
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
clientId: "xxxx",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// After performing a login via some method...
const user = await auth.getCurrentUser();
Auth.bindPhoneNumber()
is only supported in the shanghai region
Interface Description
Interface feature: Bind phone number
Interface declaration: bindPhoneNumber(params: BindPhoneRequest): Promise<void>
Input Parameters: BindPhoneRequest
| Field | Type | Required | Description |
|---|---|---|---|
| phone_number | string | Required | New phone number. Chinese phone numbers must include the country code "+86 ", e.g., "+86 138xxxxxxxxx" |
| sudo_token | string | Required | Elevated privilege token, which can be obtained via Auth.sudo |
| verification_token | string | Required | Verification code token, which can be obtained via Auth.verify |
Output Parameters: None
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
// Prerequisite: Log in first
const auth = app.auth();
// Step 1: Obtain sudo token. Refer to the Auth.sudo interface for details.
const sudo_token = "test_sudo_token";
const phone_number = "+86 13800000000";
// Step 2: User clicks to obtain the verification code, calls the following method to send the SMS verification code, and stores verificationInfo globally for convenient parameter input in Step 4
const verificationInfo = await auth.getVerification({
phone_number: phone_number,
});
// Step 3: Wait for the user to enter the SMS verification code on the page
const verificationCode = userInputCode; // 6-digit verification code
// Step 4: Verify the SMS verification code once the user has entered it
const verification_token_res = await auth.verify({
verification_id: verificationInfo.verification_id,
verification_code: verification_code,
});
const verification_token = verification_token_res.verification_token;
// Step 5: Bind the mobile phone number
await auth.bindPhoneNumber({
phone_number: phone_number,
sudo_token: sudo_token,
verification_token: verification_token,
});
Auth.bindEmail()
Interface Description
Interface feature: Email address update
Interface declaration: bindEmail(params: BindEmailRequest): Promise<void>
Input Parameters: BindEmailRequest
| Field | Type | Required | Description |
|---|---|---|---|
| string | Yes | Email address | |
| sudo_token | string | Required | Elevated privilege token, which can be obtained via Auth.sudo |
| verification_token | string | Required | Verification code token, which can be obtained via Auth.verify |
Output Parameters: None
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
// Prerequisite: Log in first
const auth = app.auth();
// Step 1: Obtain sudo token. Refer to the Auth.sudo interface for details.
const sudoToken = "test_sudo_token"
const newEmail = "new@example.com";
// Step 2: User clicks to get the verification code, call the following method to send the email verification code, store verificationInfo globally for convenient parameter input in Step 4.
const verificationInfo = await auth.getVerification({
email: newEmail
});
// Step 3: Wait for the user to enter the SMS verification code on the page
const verificationCode = userInputCode; // 6-digit verification code
// Step 4: Verify the SMS verification code once the user has entered it
const newEmailTokenRes = await auth.verify({
verification_id: verificationInfo.verification_id,
verification_code: verificationCode,
});
const verificationToken = newEmailTokenRes.verification_token
// Step 5: Bind the new email
await auth.bindEmail({
email: newEmail,
sudo_token: sudoToken
verification_token: verificationToken
});
Auth.setPassword()
Interface Description
Interface feature: Set password (update the user password when logged in)
Interface declaration setPassword(params: SetPasswordRequest): Promise<void>
Input Parameters: SetPasswordRequest
| Field | Type | Required | Description |
|---|---|---|---|
| new_password | string | Yes | New password |
| sudo_token | string | Required | Elevated privilege token, which can be obtained via Auth.sudo |
Output Parameters: None
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// Step 1: Obtain sudo token. Refer to the Auth.sudo interface for details.
const sudoToken = "test_sudo_token";
// Step 2: Update password
const newPassWord = "test_new_password";
await auth.setPassword({
new_password: newPassWord,
sudo_token: sudoToken,
});
Auth.getUserInfo()
Interface Description
Interface feature: Obtain user information
Interface declaration: getUserInfo(): Promise<UserInfo>
Input Parameters: None
Output Parameters: UserInfo
| Field | Type | Description |
|---|---|---|
| name | string | nickname (distinguished from the login username) |
| picture | string | User uploaded avatar |
| phone_number | string | User bound phone number |
| email_verified | boolean | Whether the user's email has been verified |
| birthdate | string | User birthdate |
| locale | string | User language preference |
| zoneinfo | string | Time zone |
| UserProfileProvider | UserProfileProvider | Third-party platform configuration |
UserProfileProvider
| Field | Type | Required | Description |
|---|---|---|---|
| id | string | No | Default built-in third-party provider_id, e.g. wx_open, wx_mp |
| provider_user_id | string | No | Third-party provider user id (e.g. wxopenid) |
| name | string | No | Name |
System Built-in Third-party List
| provider_id | Meaning |
|---|---|
| wx_open | WeChat Open Platform |
| wx_mp | WeChat Official Account |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const userInfo = await auth.getUserInfo();
Auth.queryUser()
Custom login scenarios and anonymous login scenarios do not support querying user information using this interface (for custom login scenarios, please query user information in your business service; anonymous login scenarios are not supported).
Interface Description
Interface feature: Query users by any of the parameters: username, email, or phone number.
Interface declaration: queryUser(queryObj: QueryUserProfileRequest): Promise<QueryUserProfileResponse>;
Input Parameters: QueryUserProfileRequest
| Field | Type | Required | Description |
|---|---|---|---|
| id | Array<string> | No | Array of user uids, supporting query for up to 50 users |
| username | string | No | Username |
| string | No | ||
| phone_number | string | No | Phone number. Chinese phone numbers must include the country code "+86 ", e.g., "+86 138xxxxxxxxx" |
Output Parameters: QueryUserProfileResponse
| Field | Type | Required | Description |
|---|---|---|---|
| total | string | No | Quantity |
| data | SimpleUserProfile[] | No | User list |
SimpleUserProfile
| Field | Type | Required | Description |
|---|---|---|---|
| sub | string | Yes | Subscript |
| name | string | Yes | Name |
| picture | string | No | Picture |
| gender | string | No | Gender |
| locale | string | No | Location |
| string | No | ||
| phone_number | string | No | Phone number |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// const email = "test@example.com";
// const phoneNumber = "+86 13800000000";
const username = "test_username";
const userInfo = await auth.queryUser({
username: username,
// email,
// phone_number: phoneNumber,
});
Auth.resetPassword()
Mobile phone number verification code method is only supported in the shanghai region
Interface Description
Interface feature: Reset password (When a user forgets the password and cannot log in, this interface can be used to forcibly set a new password)
Interface declaration: resetPassword(params: ResetPasswordRequest): Promise<void>
Input Parameters: ResetPasswordRequest
| Field | Type | Required | Description |
|---|---|---|---|
| string | No | Email address. Either email or phone_number must be used. | |
| phone_number | string | No | Phone number. Either phone_number or email must be used. For Chinese phone numbers, the country code "+86 " must be included, e.g., "+86 138xxxxxxxxx". |
| new_password | string | Yes | New password |
| verification_token | string | Required | Verification code token, which can be obtained via Auth.verify |
Output Parameters: None
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const email = "testexample.com";
const newPassword = "test_new_password";
const phoneNumber = "+86 13800000000";
// Step 1: User clicks to obtain the verification code, calls the following method to send the SMS verification code, and stores verificationInfo globally for convenient parameter input in Step 3
const verificationInfo = await auth.getVerification({
phone_number: phoneNumber,
});
// Step 2: Wait for the user to enter the SMS verification code on the page
const verificationCode = userInputCode; // 6-digit verification code
// Step 3: Verify the SMS verification code once the user has entered it
const verificationToken = await auth.verify({
verification_id: verificationInfo.verification_id,
verification_code: verificationCode,
});
await auth.resetPassword({
// email: email,
phone_number: phoneNumber,
new_password: newPassword,
verification_token: verificationToken.verificationToken,
});
Auth.isUsernameRegistered()
Interface Description
Interface feature: Check whether the username exists.
Interface declaration: isUsernameRegistered(username: string): Promise<boolean>
Input Parameters
| Field | Type | Required | Description |
|---|---|---|---|
| username | string | Yes | Username |
Output Parameters: boolean
| Value | Meaning |
|---|---|
| true | Exists |
| false | Does not exist |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const username = "your_awesome_username";
const exist = await auth.isUsernameRegistered(username);
Auth.deleteMe()
Interface Description
Interface feature: Delete user.
Interface declaration: deleteMe(params: WithSudoRequest): Promise<UserProfile>
Input Parameters: WithSudoRequest
| Field | Type | Required | Description |
|---|---|---|---|
| sudo_token | string | Required | Elevated privilege token, which can be obtained via Auth.sudo |
Output Parameters: UserProfile
| Field | Type | Description |
|---|---|---|
| sub | string | Unique user identifier) |
| name | string | Nickname (distinguished from the login username) |
| username | string | Username |
| picture | string | User uploaded avatar |
| phone_number | string | User bound phone number |
| string | User bound email | |
| email_verified | boolean | Whether the user's email has been verified |
| groups | Array<{id: string; expires_at?: string}> | List of groups/roles the user belongs to |
| gender | string | Gender |
| birthdate | string | User birthdate |
| locale | string | User language preference |
| zoneinfo | string | Time zone |
| providers | Array<UserProfileProvider> | Third-party platform configuration |
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
// 1. Obtain sudo_token via sudo operation. Refer to the Auth.sudo method.
// 2. deleteMe
const user = await auth.deleteMe({
sudo_token: "your sudo_token",
});
Auth.loginScope()
Interface Description
Interface feature: Query the user's permission scope, which can be used to determine whether it is an anonymous login state.
Interface declaration: loginScope(): Promise<string>
Input Parameters: None
Output Parameters: string
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
const username = "your_awesome_username";
// After logging in via some method...
const loginScope = await auth.loginScope();
if (loginScope === "anonymous") {
console.log("Currently using anonymous login");
}
LoginState
The LoginState object abstracts the user's current login status.
Auth.hasLoginState()
Interface Description
Interface feature: Returns the current login state LoginState, if not logged in, returns null
Interface declaration: hasLoginState(): LoginState | null
Input Parameters: None
Output Parameters: LoginState
See LoginState, returning null indicates the user is not currently logged in.
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
clientId: "xxxx",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const loginState = app.auth().hasLoginState();
if (loginState) {
// Login status valid
} else {
// No login status, or the login status has expired
}
Auth.getLoginState()
Interface Description
Interface feature: Asynchronous operation of Auth.hasLoginState(), returns the current login state LoginState, returning null indicates that the user is not currently logged in.
Interface declaration: getLoginState(): Promise<LoginState | null>
This API is the asynchronous version of hasLoginState, suitable for platforms where local storage is asynchronous, such as React Native.
Input Parameters: None
Output Parameters: LoginState
See LoginState, returning null indicates the user is not currently logged in.
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
clientId: "xxxx",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const loginState = await app.auth().getLoginState();
if (loginState) {
// Login status valid
} else {
// No login status, or the login status has expired
}
Auth.onLoginStateChanged()
Interface Description
Interface feature: Listens to login status changes. This function is triggered when the login status changes, such as when calling registration/login/logout-related APIs, or when Credentials encounter exceptions (e.g., 'credentials not found', 'no refresh token found in credentials' errors).
Interface declaration: onLoginStateChanged(callback: Function): Promise<void>
Input Parameters: OnLoginStateChangedParams
| Field | Type | Required | Description |
|---|---|---|---|
| callback | Function | Yes | Callback function |
callback Function Input Parameters Definition
| Field | Type | Description |
|---|---|---|
| name | string | Default value is loginStateChanged |
| data | object | Includes { msg?: string; eventType: 'sign_in' | 'sign_out' | 'credentials_error' } |
If the eventType is sign_in or sign_out, the current login state LoginState will also be returned.
Output Parameters: None
Sample Code
const app = cloudbase.init({
env: "xxxx-yyy",
clientId: "xxxx",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
app.auth().onLoginStateChanged((params) => {
console.log(params);
const { eventType } = params?.data || {};
switch (eventType) {
case "sign_in":
// Login successful
break;
case "sign_out":
// Logout successful
break;
case "credentials_error":
// Permission invalid
break;
default:
return;
}
});
LoginState.user
Type: User | null
Represents the current user. For details, see User
If not logged in, it is null
User
User.update()
Interface Description
Interface feature: Update user information
Interface declaration: update(userInfo): Promise<void>
Input Parameters: userInfo
| Field | Type | Required | Description |
|---|---|---|---|
| name | string | No | nickname (distinguished from the login username) |
| username | string | No | Username |
| picture | string | No | User uploaded avatar |
| phone_number | string | No | User bound phone number |
| string | No | User bound email | |
| gender | string | No | Gender. Valid values: MALE, FEMALE, UNKNOWN |
| birthdate | string | No | User birthdate |
Output Parameters: None
Sample Code
const user = auth.currentUser;
user
.update({
gender: gender: "MALE", // Gender. Valid values: MALE, FEMALE, UNKNOWN
})
.then(() => {
// Update user information successful
});
User.refresh()
Interface Description
Interface feature: Refresh local user information. When a user updates their information on another client, they can call this interface to synchronize the updated information.
Interface declaration: refresh(): Promise<UserInfo>
Input Parameters: None
Output Parameters: UserInfo
| Field | Type | Description |
|---|---|---|
| sub | string | unique user identifier) |
| name | string | nickname (distinguished from the login username) |
| username | string | Username |
| picture | string | User uploaded avatar |
| phone_number | string | User bound phone number |
| string | User bound email | |
| email_verified | boolean | Whether the user's email has been verified |
| groups | Array<{id: string; expires_at?: string}> | List of groups/roles the user belongs to (string array) |
| gender | string | Gender |
| birthdate | string | User birthdate |
| locale | string | User-configured language |
| zoneinfo | string | Time zone |
| providers | Array<UserProfileProvider> | Third-party platform configuration |
Sample Code
const user = auth.currentUser;
user.refresh().then((userInfo) => {
// Refresh user information successful
});
Error Codes
Login Error
| Error Code | Description |
|---|---|
| not_found | User not found |
| password_not_set | The current user has not set a password. Please use verification code login or third-party login. |
| invalid_password | Incorrect password |
| user_pending | The user is not activated |
| user_blocked | The user is deactivated |
| invalid_status | You have exceeded the maximum number of password retries. Please try again later. |
| invalid_two_factor | Two-factor code does not match or is expired |
Registration Error
| Error Code | Description |
|---|---|
| failed_precondition | The phone number or email you entered has already been registered. Please use a different phone number or email. |
Verification Code Related Errors
| Error Code | Description |
|---|---|
| failed_precondition | Failed to obtain user information from a third party |
| resource_exhausted | You have attempted too frequently. Please try again later. |
| invalid_argument | The verification code you entered is incorrect or has expired |
| aborted | You have attempted too many times. Please return to the homepage and try again later. |
| permission_denied | Your current session has expired. Please go back and try again. |
| captcha_required | Verification code is required; please integrate with the anti-bot service |
| captcha_invalid | Invalid verification code; please integrate with the anti-bot service |
Other Errors
| Error Code | Description |
|---|---|
| unreachable | Network error. Please check your network connection and try again later. |
Error Description
| Error Code | Error Description | Description |
|---|---|---|
| permission_denied | cors permission denied,please check if {url} in your client {env} domains | Please check in "TCB platform - Environment Configuration - Allowed Origins - Security Domains" whether the security domain {url} has been configured in the corresponding {env} environment. It takes effect 10 minutes after configuration. |
Verification Code Related Handling
error==captcha_required or error==captcha_invalid indicates that the request triggered captcha-related logic. Machine verification is required.
After the captcha process is completed, if the business interface returns error equal to captcha_required, it indicates that the request requires the captcha_token parameter; use a local, non-expired captcha whenever possible. When error equals captcha_invalid, it indicates that the captcha is invalid and a new captcha needs to be obtained. Within the same verification process, captcha_invalid can be retried at most once.
To use the adapter for processing, see the Captcha Processing Guide for adapter
Initialize captcha
curl -X POST "https://${env}.ap-shanghai.tcb-api.tencentcloudapi.com/auth/v1/captcha/init" \
-H "Content-Type:application/json" \
-u ${clientID}:${clientSecrect}
-d \
'{
"redirect_uri": "https://example.com/callback",
"state": "your_state string"
}'
Request Parameters
redirect_uri: (Required) The URL to redirect to after captcha verification completes. state: (Required) System state string, which is passed back after captcha verification completes.
Response 1: Status code 200 with a non-empty url field returned, indicating that the captcha needs to be displayed and verified
If user requests are too frequent or there are other risks, the captcha service will return a response in the following format.
{
"url": "https://exmaple.com/captcha.html",
"expires_in": 600
}
This indicates that user actions must pass captcha verification to proceed. After the request succeeds, the client opens the url via a browser, webview/iframe, etc., for example: https://exmaple.com/captcha.html. After the user completes the process in the web, they will be automatically redirected to the following address: (where captcha_token is the captcha token, and expires_in is the expiration time in seconds) https://example.com/callback?state=xxxxx&captcha_token=hbGciOiJeyJhbGciOiJSUAeyJhbGciOiJ&expires_in=600
The business side needs to monitor the URL changes of redirect_uri. When the URL becomes appanme://com.package.name/callback, verify whether the state matches the one passed in, and obtain captcha_token and expires_in.
If an error occurs during the verification process, the captcha page will display an error message. After the user clicks the back button, the captcha page appends the error and error_description to the redirect_uri and redirects, for example:
https://example.com/callback?state=xxxxx&error=xxx&error_description=xxx
At this point, the business side may restore the initial page or perform other processing as needed.
Response 2: Status code is not 200, error handling is required.
If user requests are too frequent or there are other risks, the captcha service will return a response in the following format.
{
"error": "resource_exhausted",
"error_description": "Your operation is too frequent, please try again later"
}
At this point, the client needs to display the error_description, which can be combined with i18n for multilingual presentation.
Obtain the captcha_token and request again
After obtaining the captcha_token, add it to the url parameters and make the request;
For example, if a request to /v1/example returns a captcha_invalid error, you need to request /v1/example?captcha_token=hbGciOiJeyJhbGciOiJSUAeyJhbGciOiJ again to complete the operation.
Type Definitions
User
The User object abstracts the current user's information.
| Property | Type | Desc |
|---|---|---|
| uid | string | undefined | Unique user identifier |
| gender | string | undefined | Gender |
| picture | string | undefined | Avatar URL |
| string | undefined | ||
| emailVerified | boolean | undefined | Whether the email has been verified |
| phoneNumber | string | undefined | Phone number |
| username | string | undefined | Username |
| name | string | undefined | Nickname |
| providers | Array<{ id?: string; providerUserId?: string; name?: string }> | undefined | List of third-party login bindings |
| birthdate | string | undefined | Date of birth |
| sub | string | undefined | Subject identifier (JWT sub) |
Credentials
Credentials object defines the structure of credential information for authentication and authorization.
| Property | Type | Desc |
|---|---|---|
| token_type | string | null | Token type, commonly values such as Bearer, indicating the authentication scheme of the token |
| access_token | string | null | Access token used as a credential to access protected resources |
| refresh_token | string | null | Refresh token used to obtain a new access token after it expires |
| scope | string | null | Scope of permissions, typically a space-delimited string (e.g., "openid profile email") |
| expires_in | number | null | Validity period of the access token, measured in seconds |
| expires_at | Date | null | Expiration time of the access token |
| sub | string | null | Unique user identifier |
| groups | string[] | null | List of groups/roles the user belongs to |
| version | string | Version number or source identifier of the credential |
LoginState
The LoginState object abstracts the user's current login status.
| Property | Type | Description |
|---|---|---|
| user | User | User object |
| oauthLoginState | Credentials | null | Credentials object |