Skip to main content

Authentication

Note

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

danger

@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();
Note

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

FieldTypeRequiredDescription
phone_numberstringNoThe phone number used for registration. Either phone_number or email must be used.
emailstringNoThe email used for registration. Either phone_number or email must be used.
verification_codestringNoThe verification code, which can be obtained via Auth.getVerification
verification_tokenstringNoThe verification code token, which can be obtained via Auth.verify
provider_tokenstringNoThe third-party provider token, used to bind third-party user information, which can be obtained via Auth.grantProviderToken
passwordstringNoPassword
namestringNoUsername
genderstringNoGender
picturestringNoAvatar
localestringNoAddress

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

Note

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

FieldTypeRequiredDescription
usernamestringRequiredUser's phone number, email, or custom username. If it is a Chinese phone number, include the country code "+86", for example, "+86 138xxxxxxxxx".
passwordstringNoUser password. Either password or verification_token must be provided.
verification_tokenstringNoThe 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

FieldTypeRequiredDescription
redirect_uristringNoRedirect URL after sign out
statestringNoWhen 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

FieldTypeDescription
redirect_uristringThe 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

FieldTypeDescription
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()

Note

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

FieldTypeRequiredDefault ValueDescription
useWxCloudbooleanNotruetrue: 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()

Note

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

Note

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

FieldTypeRequiredDefault ValueDescription
phoneCodestringYesEmptyWeChat 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()

Note

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

FieldTypeRequiredDefaultDescription
verificationInfoobjectVerification token information{}Return value of Auth.getVerification
verificationCodestringVerification codeemptyThe obtained SMS verification code will be sent after calling Auth.getVerification
phoneNumstringPhone numberemptyThe 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

FieldTypeRequiredDefaultDescription
verificationInfoobjectVerification token information{}Return value of Auth.getVerification
verificationCodestringVerification codeemptyObtained email verification code, which will be sent after calling Auth.getVerification
emailstringEmailemptyEmail 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()

Note

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

FieldTypeMeaningDefault ValueDescription
config_versionstringLogin configuration version for the default login pageenv1. '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_uristringRedirect URL after loginDefaults to the current page URL
app_idstringApplication idEmptyRequired when config_version is not 'env', e.g., app-xxx
queryobjectParameters to be carried when redirecting to the default login pageEmpty

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",
});

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

FieldTypeRequiredDescription
provider_idstringYesThird-party platform ID, refer to the built-in third-party platforms list
provider_redirect_uristringYesThird-party platform redirect Uri. After authorization is completed, the redirect url will carry a code parameter.
statestringYesUser-defined state identifier field to identify the source of third-party platform callbacks
other_params{sign_out_uri?:string}NoOther parameters

Output Parameters: GenProviderRedirectUriResponse

FieldTypeRequiredDescription
uristringYesClient request
signout_uristringYesSign-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

FieldTypeRequiredDescription
provider_idstringYesThird-party platform ID, refer to the built-in third-party list
provider_redirect_uristringNoredirect uri for third-party platform
provider_codestringNoThird-party platform authorization code (carried in the redirect uri)
provider_access_tokenstringNoThird-party platform access token (carried in the redirect uri)
provider_id_tokenstringNoThird-party platform ID token (carried in the redirect uri)

Output Parameters: GrantProviderTokenResponse

FieldTypeRequiredDescription
provider_tokenstringYesThird-party platform token
expires_innumberYesValidity period
provider_profileProviderProfileNoThird-party identity source information
ProviderProfile
FieldTypeRequiredDescription
provider_idstringYesDefault built-in third-party provider IDs: wx_open, wx_mp
substringYesThird-party user id (e.g. wxopenid)
namestringNoName
phone_numberstringNoPhone number
picturestringNoAvatar
metaProviderProfileMetaNoExtended information of third-party identity source (returned by mini-program)
ProviderProfileMeta
FieldTypeRequiredDescription
appidstringNoThe mini-program's appid
openidstringNoThe 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

FieldTypeRequiredDescription
provider_tokenstringYesThird-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

FieldTypeRequiredDescription
provider_idstringYesThird-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

FieldTypeRequiredDescription
idstringYesThird-party platform ID
provider_user_idstringYesThird-party platform user ID
namestringYesThird-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

FieldTypeRequiredDescription
provider_tokenstringYesThird-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,
});

Auth.verify()

Note

"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

FieldTypeRequiredDescription
verification_codestringYesThe verification code, which can be obtained via Auth.getVerification
verification_idstringYesThe verification code ID, which can be obtained via Auth.getVerification

Output Parameters: VerifyResponse

FieldTypeRequiredDescription
verification_tokenstringNoVerification 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()

Note

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

FieldTypeRequiredDescription
phone_numberstringNoPhone number. For Chinese phone numbers, the country code "+86 " must be included, e.g., "+86 138xxxxxxxxx". Either phone_number or email must be used.
emailstringNoEmail address. Either email or phone_number must be used.
targetTargetNoThe application scenario for phone number or email.
Target
ValueMeaning
ANYDoes not verify the existence of the phone number or email. Use case: registration or login scenarios without an existing login state.
USERThe phone number or email must exist in the system and be bound to a user.

Output Parameters: GetVerificationResponse

FieldTypeDescription
verification_idstringVerification code id
is_userbooleanWhether 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

FieldTypeRequiredDescription
passwordstringNoPassword. Either password or verification_token must be chosen. If a phone number is bound, then verification_token must be used for sudo.
verification_tokenstringNotoken obtained by verifying the bound phone number or email, which can be acquired via Auth.verify

Output Parameters: SudoResponse

FieldTypeDescription
sudo_tokenstringElevated 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

FieldTypeDescription
accessTokenstringAccess token
envstringEnvironment 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);

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

Note

is only supported in the shanghai region

Interface Description

Interface feature: Bind phone number

Interface declaration: bindPhoneNumber(params: BindPhoneRequest): Promise<void>

Input Parameters: BindPhoneRequest

FieldTypeRequiredDescription
phone_numberstringRequiredNew phone number. Chinese phone numbers must include the country code "+86 ", e.g., "+86 138xxxxxxxxx"
sudo_tokenstringRequiredElevated privilege token, which can be obtained via Auth.sudo
verification_tokenstringRequiredVerification 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

FieldTypeRequiredDescription
emailstringYesEmail address
sudo_tokenstringRequiredElevated privilege token, which can be obtained via Auth.sudo
verification_tokenstringRequiredVerification 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

FieldTypeRequiredDescription
new_passwordstringYesNew password
sudo_tokenstringRequiredElevated 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

FieldTypeDescription
namestringnickname (distinguished from the login username)
picturestringUser uploaded avatar
phone_numberstringUser bound phone number
email_verifiedbooleanWhether the user's email has been verified
birthdatestringUser birthdate
localestringUser language preference
zoneinfostringTime zone
UserProfileProviderUserProfileProviderThird-party platform configuration
UserProfileProvider
FieldTypeRequiredDescription
idstringNoDefault built-in third-party provider_id, e.g. wx_open, wx_mp
provider_user_idstringNoThird-party provider user id (e.g. wxopenid)
namestringNoName
System Built-in Third-party List
provider_idMeaning
wx_openWeChat Open Platform
wx_mpWeChat 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()

danger

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

FieldTypeRequiredDescription
idArray<string>NoArray of user uids, supporting query for up to 50 users
usernamestringNoUsername
emailstringNoEmail
phone_numberstringNoPhone number. Chinese phone numbers must include the country code "+86 ", e.g., "+86 138xxxxxxxxx"

Output Parameters: QueryUserProfileResponse

FieldTypeRequiredDescription
totalstringNoQuantity
dataSimpleUserProfile[]NoUser list
SimpleUserProfile
FieldTypeRequiredDescription
substringYesSubscript
namestringYesName
picturestringNoPicture
genderstringNoGender
localestringNoLocation
emailstringNoEmail
phone_numberstringNoPhone 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()

Note

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

FieldTypeRequiredDescription
emailstringNoEmail address. Either email or phone_number must be used.
phone_numberstringNoPhone 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_passwordstringYesNew password
verification_tokenstringRequiredVerification 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

FieldTypeRequiredDescription
usernamestringYesUsername

Output Parameters: boolean

ValueMeaning
trueExists
falseDoes 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

FieldTypeRequiredDescription
sudo_tokenstringRequiredElevated privilege token, which can be obtained via Auth.sudo

Output Parameters: UserProfile

FieldTypeDescription
substringUnique user identifier)
namestringNickname (distinguished from the login username)
usernamestringUsername
picturestringUser uploaded avatar
phone_numberstringUser bound phone number
emailstringUser bound email
email_verifiedbooleanWhether the user's email has been verified
groupsArray<{id: string; expires_at?: string}>List of groups/roles the user belongs to
genderstringGender
birthdatestringUser birthdate
localestringUser language preference
zoneinfostringTime zone
providersArray<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>

Note

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

FieldTypeRequiredDescription
callbackFunctionYesCallback function
callback Function Input Parameters Definition
FieldTypeDescription
namestringDefault value is loginStateChanged
dataobjectIncludes { msg?: string; eventType: 'sign_in' | 'sign_out' | 'credentials_error' }
Note

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

FieldTypeRequiredDescription
namestringNonickname (distinguished from the login username)
usernamestringNoUsername
picturestringNoUser uploaded avatar
phone_numberstringNoUser bound phone number
emailstringNoUser bound email
genderstringNoGender. Valid values: MALE, FEMALE, UNKNOWN
birthdatestringNoUser 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

FieldTypeDescription
substringunique user identifier)
namestringnickname (distinguished from the login username)
usernamestringUsername
picturestringUser uploaded avatar
phone_numberstringUser bound phone number
emailstringUser bound email
email_verifiedbooleanWhether the user's email has been verified
groupsArray<{id: string; expires_at?: string}>List of groups/roles the user belongs to (string array)
genderstringGender
birthdatestringUser birthdate
localestringUser-configured language
zoneinfostringTime zone
providersArray<UserProfileProvider>Third-party platform configuration

Sample Code

const user = auth.currentUser;

user.refresh().then((userInfo) => {
// Refresh user information successful
});

Error Codes

Login Error

Error CodeDescription
not_foundUser not found
password_not_setThe current user has not set a password. Please use verification code login or third-party login.
invalid_passwordIncorrect password
user_pendingThe user is not activated
user_blockedThe user is deactivated
invalid_statusYou have exceeded the maximum number of password retries. Please try again later.
invalid_two_factorTwo-factor code does not match or is expired

Registration Error

Error CodeDescription
failed_preconditionThe phone number or email you entered has already been registered. Please use a different phone number or email.
Error CodeDescription
failed_preconditionFailed to obtain user information from a third party
resource_exhaustedYou have attempted too frequently. Please try again later.
invalid_argumentThe verification code you entered is incorrect or has expired
abortedYou have attempted too many times. Please return to the homepage and try again later.
permission_deniedYour current session has expired. Please go back and try again.
captcha_requiredVerification code is required; please integrate with the anti-bot service
captcha_invalidInvalid verification code; please integrate with the anti-bot service

Other Errors

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

Error Description

Error CodeError DescriptionDescription
permission_deniedcors permission denied,please check if {url} in your client {env} domainsPlease 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.

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.

PropertyTypeDesc
uidstring | undefinedUnique user identifier
genderstring | undefinedGender
picturestring | undefinedAvatar URL
emailstring | undefinedEmail
emailVerifiedboolean | undefinedWhether the email has been verified
phoneNumberstring | undefinedPhone number
usernamestring | undefinedUsername
namestring | undefinedNickname
providersArray<{ id?: string; providerUserId?: string; name?: string }> | undefinedList of third-party login bindings
birthdatestring | undefinedDate of birth
substring | undefinedSubject identifier (JWT sub)

Credentials

Credentials object defines the structure of credential information for authentication and authorization.

PropertyTypeDesc
token_typestring | nullToken type, commonly values such as Bearer​, indicating the authentication scheme of the token
access_tokenstring | nullAccess token used as a credential to access protected resources
refresh_tokenstring | nullRefresh token used to obtain a new access token after it expires
scopestring | nullScope of permissions, typically a space-delimited string (e.g., "openid profile email")
expires_innumber | nullValidity period of the access token, measured in seconds
expires_atDate | nullExpiration time of the access token
substring | nullUnique user identifier
groupsstring[] | nullList of groups/roles the user belongs to
versionstringVersion number or source identifier of the credential

LoginState

The LoginState object abstracts the user's current login status.

PropertyTypeDescription
userUserUser object
oauthLoginStateCredentials | nullCredentials object