Skip to main content

authentication

Identity Verification

Note

Under the new login system, ensure one environment corresponds to one tcb instance (avoid initializing tcb instances in the same environment multiple times).

App.auth()

API description

Return the Auth object. Identity verification related attributes and methods are in the Auth object.

interface declaration: auth(): Auth

danger

@cloudbase/js-sdk@2.x supports only the local method (Web clients retain authentication status for 30 days before explicit logout) to store identity status. (The session and none modes in version 1.x are no longer supported.)

Example 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

Note

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

Auth.signUp()

API description

API feature: Register a user. Currently supports phone number verification code registration and mailbox verification code registration. For more detailed process, see user registration.

interface declaration: signUp(params: SignUpRequest): Promise<LoginState>

API input parameter: SignUpRequest

FieldTypeRequiredDescription
phone_numberstringNoMobile number used for registration. You must choose either phone_number or email.
emailstringNoMailbox used for registration. You must choose either phone_number or email.
verification_codestringNoVerification code, which can be obtained by calling Auth.getVerification
verification_tokenstringNoCaptcha token, which can be obtained by calling Auth.verify
provider_tokenstringNoThird-party provider token, used to bind third-party user info, which can be obtained via Auth.grantProviderToken
passwordstringNoPassword
namestringNoUsername
genderstringNoGender
picturestringNoAvatar
localestringNoAddress
usernamestringNoUsername, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed

API output parameter: LoginState

See LoginState

Example code

// Initialize 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: Sign up with phone number verification code

Step one: User click Get Verification Code, use the following method to send SMS verification code, and store verificationInfo in global for parameter input in step 3.
const phoneNumber = "+86 13800000000";
const verification = await auth.getVerification({
phone_number: phoneNumber,
});

// If using mailbox verification, change the code in step one to
{
const email = "test@example.com";
const verification = await auth.getVerification({
email: email,
});
}

verification code verification
// After calling the SMS API, the mobile phone will receive a cloud development SMS verification code.
// The user fills in the SMS verification code and can call the API to verify.

Step 2: Wait for the user to manually input the SMS verification code on the page.
const verificationCode = userInputCode; // 6-digit verification code

Step 3: Verify the SMS verification code after the user enters the verification code.
const verificationTokenRes = await auth.verify({
verification_id: verification.verification_id,
verification_code: verificationCode,
});

Step 4: Register
// If this 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,
// Option, set nickname
name: "phone user",
// Optional, set password.
password: "password",
// Optional, set login username
username: "username",
});
}

Auth.signIn()

Note

Mobile number-based login is only supported in the Shanghai region

API description

API feature: After registration completion, this method can be used to perform user login. Currently supports mobile number, mailbox, and username and password login. For detailed process of username and password login, see account login.

interface declaration: signIn(params: SignInRequest): Promise<LoginState>

API input parameter: SignInRequest

FieldTypeRequiredDescription
usernamestringYesUser mobile number, mailbox or custom username. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx".
passwordstringNoUser password. Choose either password or verification_token.
verification_tokenstringNoCaptcha token. You must choose either password or verification_token, which can be obtained by calling Auth.verify

API output parameter: LoginState

See LoginState

Example 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: Login by mobile number
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()

API description

API feature: logout

interface declaration: signOut(params?: SignoutRequest): Promise<SignoutReponse>

API input parameter: SignoutRequest

FieldTypeRequiredDescription
redirect_uristringNoThe redirect page host address after exiting
statestringNoWhen there is a redirect_uri, this parameter is placed in the state link parameter of redirect_uri for case-sensitive identity source

API output parameter: SignoutResponse

FieldTypeDescription
redirect_uristringThe redirect page host address. There will be a return if redirect_uri is passed in the input or third-party authentication is configured with redirect_uri

Example code

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

const auth = app.auth();

// Listen to login state changes
auth.onLoginStateChanged((params) => {
console.log(params);
const { eventType } = params?.data || {};
switch (eventType) {
case "sign_in":
// Login is successful
break;
case "sign_out":
// Logout is successful
break;
case "credentials_error":
// Permission expired
break;
default:
return;
}
});

await auth.signOut();

Auth.signInAnonymously()

API description

API feature: Anonymous login. For the detailed process, see anonymous login.

interface declaration: signInAnonymously(): Promise<LoginState>

API input parameter: None

API output parameter: LoginState

See LoginState

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

Auth.setCustomSignFunc()

API description

API feature: set the custom login ticket function

interface declaration: setCustomSignFunc(getTickFn: GetCustomSignTicketFn): void

API input parameter: GetCustomSignTicketFn

FieldTypeDescription
getTickFn() => Promise<string>The function to get the custom login ticket

API output parameter: None

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

API description

API feature: Custom login, used in conjunction with Auth.setCustomSignFunc. For detailed process, see custom login.

interface declaration: signInWithCustomTicket(): Promise<LoginState>

API input parameter: None

API output parameter: LoginState

See LoginState

Example 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

Only supported for use in WeChat mini program

API description

API feature: Silent login with WeChat mini program openId. 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 Cloud Development Platform - Log-in Methods (https://tcb.cloud.tencent.com/dev?envId=#/identity/login-manage).

interface declaration: signInWithOpenId(params?: SignInWithOpenIdReq): Promise<LoginState>

API input parameter: SignInWithOpenIdReq

FieldTypeRequiredDefault ValueDescription
useWxCloudbooleanNotruetrue: Use WeChat Cloud Development mode to handle request, enable mini program WeChat Cloud Development environment; false: Use ordinary http request

API output parameter: LoginState

See LoginState

Example 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

Only supported for use in WeChat mini program

API description

API feature: Silent login with WeChat mini program unionId. 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 Cloud Development Platform - Log-in Methods (https://tcb.cloud.tencent.com/dev?envId=#/identity/login-manage).

interface declaration: signInWithUnionId(): Promise<LoginState>

API input parameter: None

API output parameter: LoginState

See LoginState

Example 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

Only supported for use in WeChat mini program

API description

API feature: WeChat mini program mobile phone authorization login. If the user does not exist, it will determine whether to automatically register based on the login mode configuration of the corresponding identity source in Cloud Development Platform - Login Methods.

interface declaration: signInWithPhoneAuth(params: SignInWithPhoneAuthReq): Promise<LoginState>

API input parameter: SignInWithPhoneAuthReq

fielddata typerequireddefault valuedescription
phoneCodestringyesemptyWeChat mini program mobile phone authorization code, obtained via WeChat mini program mobile number quick verification component

API output parameter: LoginState

See LoginState

Example 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

Shanghai region only supported

API description

API feature: Log in via SMS verification code. For detailed process, see SMS verification code login.

interface declaration: signInWithSms(params: SignInWithSmsReq): Promise<LoginState>

API input parameter: SignInWithSmsReq

FieldTypeRequiredDefault ValueDescription
verificationInfoobjectCaptcha token information{}Returned value of Auth.getVerification
verificationCodestringverification codeemptyObtained SMS verification code. A verification code will be sent after calling Auth.getVerification
phoneNumstringMobile numberEmptyThe mobile number to obtain the Captcha. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx".

API output parameter: LoginState

See LoginState

Example 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 one: The user clicks Get Verification Code, use the following method to send the SMS verification code, and store verificationInfo in global for step 3 as parameter input.
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: After the user enters the verification code, verify the SMS verification code and log in.
await auth.signInWithSms({
verificationInfo,
verificationCode, // SMS verification code from user input
phoneNum: phoneNumber, // user mobile number
});

Auth.signInWithEmail()

API description

API feature: Log in via email verification code. For detailed process, see Email verification code login.

interface declaration: signInWithEmail(params: SignInWithEmailReq): Promise<LoginState>

API input parameter: SignInWithEmailReq

FieldTypeRequiredDefault ValueDescription
verificationInfoobjectCaptcha token information{}Returned value of Auth.getVerification
verificationCodestringverification codeemptyObtained mailbox verification code. A verification code will be sent after calling Auth.getVerification
emailstringmailboxemptyemail address to get verification code

API output parameter: LoginState

See LoginState

Example 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 one: User click to get the verification code, use the following method to send the mailbox verification code, and store verificationInfo in global for step 3 as parameter input.
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 enters the verification code, verify the email code and log in.
await auth.signInWithEmail({
verificationInfo,
verificationCode, // Email verification code from user input
email: email, // User email
});

Auth.toDefaultLoginPage()

Note

To use this function, upgrade @cloudbase/js-sdk to version 2.18.0 or later.

API description

API feature: redirect to the system default login page, fully compatible with web and WeChat mini program.

interface declaration: toDefaultLoginPage(params: authModels.ToDefaultLoginPage): Promise<void>

API input parameter: ToDefaultLoginPage

FieldTypeMeaningDefault ValueDescription
config_versionstringLogin configuration version of the default login pageenv1. 'env' means managed login page configuration, can be set in Cloud Development Platform - Identity Verification. 2. Non-'env' means using independent managed login page configuration, can be set in "Cloud Development Platform - Visual Low Code - Access Control". The appropriate config_version can be obtained from the parameter access of the __auth login page URLs in automatic redirection.
redirect_uristringRedirection address after loginDefaults to current page address
app_idstringapplication idemptyrequired item when config_version is not 'env', for example app-xxx
queryobjectParameters to carry when navigating to the default login pageempty

API output parameter: None

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

Debug locally

If you develop a Web application, since the static resources of the __auth Login page are stored in Website Hosting (https://tcb.cloud.tencent.com/dev?envId=#/static-hosting), you need to configure a proxy during local debugging to successfully redirect to the __auth Login page.

Recommended to use the Whistle tool for proxy configuration. The Access domain of the __auth Login page can be viewed in Website Hosting - configuration message - default domain name.

Assume the Access Address of the locally started application is http://localhost:3000 and the Access domain of the __auth Login page is lowcode-xxx-xxx.tcloudbaseapp.com, the Rules configuration of the Whistle proxy is as follows:

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

# Configure proxy for other application paths

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

Third-Party Platform Login

Auth.genProviderRedirectUri()

API description

API feature: Generate authorization Uri for third-party platform (for example WeChat QR code scan code for authorization web page)

interface declaration: genProviderRedirectUri(params: GenProviderRedirectUriRequest): Promise<GenProviderRedirectUriResponse>

API input parameter: GenProviderRedirectUriRequest

FieldTypeRequiredDescription
provider_idstringYesThird-party platform ID, see system built-in third-party platform list
provider_redirect_uristringYesThe third-party platform redirection uri. After authorization is completed, the url will carry the code parameter during redirection.
statestringYesUser-defined status identifier field to identify third-party platform callback source
other_params{sign_out_uri?:string}NoOther parameters

API output parameter: GenProviderRedirectUriResponse

FieldTypeRequiredDescription
uristringYesClient request
signout_uristringYesLogout Uri

Example 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 status identifier field
const otherParams = { sign_out_uri: "test_sign_out_uri" }; // Other parameters

// Third-party platform authorization-based login example

// 1. Get the authorization page address of a third-party platform (for example Weixin authorization)
const { uri } = await auth.genProviderRedirectUri({
provider_id: providerId,
provider_redirect_uri: providerUri,
state: state,
other_params: otherParams,
});

// 2. Visit the URI (for example location.href = uri)

// 3. Authorize (for example WeChat Scan Code Authorization)

// 4. Call back to the provider_redirect_uri address (the url query carries parameters such as the authorization code and state). At this point, check whether the state meets expectations (for example wx_open set by oneself).
const provider_code = "your provider code";

// 5. If the state behaves as expected (WeChat open platform authorization wx_open), obtain the third-party platform token.
const { provider_token } = await auth.grantProviderToken({
provider_id: "wx_open",
provider_redirect_uri: "cur page", // specify the url address for the third-party platform to jump back to
provider_code: provider_code, // code parameter carried in url param when the third-party platform jumps back to the webpage
});

// 6. Log in only or log in and register via provider_token (related to Cloud Development Platform login methods identity source mode configuration)
await auth.signInWithProvider({
provider_token,
});

Auth.grantProviderToken()

API description

API feature: provide third-party platform login token

interface declaration: grantProviderToken(params: GrantProviderTokenRequest): Promise<GrantProviderTokenResponse>

API input parameter: GrantProviderTokenRequest

FieldTypeRequiredDescription
provider_idstringYesThird-party platform ID, see system built-in third-party list
provider_redirect_uristringNoThird-party platform redirect uri
provider_codestringNoThird-party platform authorization code (carried in redirect uri)
provider_access_tokenstringNoThird-party platform access token (carried in redirect uri)
provider_id_tokenstringNoThird-party platform ID token (carried in redirect uri)

API output parameter: GrantProviderTokenResponse

FieldTypeRequiredDescription
provider_tokenstringYesThird-party platform token
expires_innumberRequiredValid period
provider_profileProviderProfileNoThird-party identity source info
ProviderProfile
FieldTypeRequiredDescription
provider_idstringRequiredDefault built-in third-party providerid, wx_open, wx_mp
substringYesThird-party user id (such as wxopenid)
namestringNoName
phone_numberstringNoMobile number
picturestringNoAvatar
metaProviderProfileMetaNoExtended information of third-party identity source (returned by mini program)
ProviderProfileMeta
FieldTypeRequiredDescription
appidstringNoMini program appid
openidstringNoMini program openid

Example 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: "cur page", // specify the url address for the third-party platform to jump back to
provider_code: "provider code", // code parameter carried in url param when the third-party platform jumps back to the webpage
});

Auth.signInWithProvider()

API description

API 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 Cloud Development Platform - Login Methods.

interface declaration: signInWithProvider(params: SignInWithProviderRequest): Promise<LoginState>

API input parameter: SignInWithProviderRequest

FieldTypeRequiredDescription
provider_tokenstringYesThird-party platform token, which can be obtained via Auth.grantProviderToken

API output parameter: LoginState

See LoginState

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

API description

API feature: Unbind third-party

interface declaration: unbindProvider(params: UnbindProviderRequest): Promise<void>

API input parameter: UnbindProviderRequest

FieldTypeRequiredDescription
provider_idstringYesThird-party platform ID, see the response packet during binding, obtain via Auth.getProviders

API output parameter: None

Example code

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

const auth = app.auth();

// After completing login

// Get the bound third-party platform ID
const { id } = await auth.getProviders();

await auth.unbindProvider({
provider_id: id,
});

Auth.getProviders()

API description

API feature: Get third-party bound list

interface declaration: getProviders(): Promise<UserProfileProvider>

API input parameter: None

API output parameter: UserProfileProvider

FieldTypeRequiredDescription
idstringYesThird-party platform ID
provider_user_idstringYesThird-party platform user ID
namestringYesThird-party platform Nickname

Example code

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

const auth = app.auth();

// After completing login

await auth.getProviders();

Auth.bindWithProvider()

API description

API feature: bind third-party login

interface declaration: bindWithProvider(params: BindWithProviderRequest): Promise<void>

API input parameter: BindWithProviderRequest

FieldTypeRequiredDescription
provider_tokenstringYesThe third-party platform authorization token, which can be obtained via Auth.grantProviderToken

API output parameter: None

Example code

const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // defaults to Shanghai region if not specified
});
const provider_token = "test_provider_token"; // see Auth.grantProviderToken to get

const auth = app.auth();
await auth.bindWithProvider({
provider_token,
});

Auth.verifyCaptchaData()

API description

API feature: Verify graphic verification code data, used for custom adapter or handling graphic verification code verification process when using adapter.

interface declaration: verifyCaptchaData(params: VerifyCaptchaDataRequest): Promise<CaptchaToken>

API input parameter: VerifyCaptchaDataRequest

FieldTypeRequiredDescription
tokenstringYesCaptcha token, obtained from the URL parameter in the captchaOptions.openURIWithCallback callback of the adapter
keystringYesThe answer to the graphic verification code in user input

API output parameter: CaptchaToken

FieldTypeDescription
captcha_tokenstringThe verify token returned after verification passes
expires_innumberToken valid period (seconds)

Example code

import cloudbase from "@cloudbase/js-sdk";

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

const auth = app.auth();

for use in custom adapter
const adapter = {
Other adapter configurations...
captchaOptions: {
openURIWithCallback: async (url) => {
// Parse URL parameters
const urlObj = new URL(url);
const captchaData = urlObj.searchParams.get("captcha_data") || ""; // Base64 encoded Captcha image
const state = urlObj.searchParams.get("state") || "";
const token = urlObj.searchParams.get("token") || "";

// 1. Show the Captcha image to users (captchaData is Base64 encoded image data)
// 2. Wait for user input validation
const userInputKey = await showCaptchaDialogAndGetUserInput(captchaData);

// 3. Call verifyCaptchaData to validate user input
const captchaToken = await auth.verifyCaptchaData({
token: token,
key: userInputKey, // user input verification code
});

return captchaToken;
},
},
};
Usage scenario

When cloud development detects a need for graphic Captcha verification (such as frequent login or other sensitive operations), it triggers the captchaOptions.openURIWithCallback callback of the adapter. Developers need to:

  1. Parse parameters such as captcha_data (verification code image) and token from the callback URL.
  2. Display the verification code image to users
  3. Retrieve the user-entered Captcha answer
  4. Call the verifyCaptchaData API to validate and obtain captchaToken
  5. Return captchaToken as the Promise's returned value :::

Auth.verify()

SMS verification code is only supported in the Shanghai region :::

API description

API feature: verification code verification, including SMS verification code and mailbox verification code

interface declaration: verify(params: VerifyRequest): Promise<VerifyResponse>

API input parameter: VerifyRequest

FieldTypeRequiredDescription
verification_codestringYesVerification code, which can be obtained by calling Auth.getVerification
verification_idstringYesCaptcha ID, which can be obtained by calling Auth.getVerification

API output parameter: VerifyResponse

FieldTypeRequiredDescription
verification_tokenstringNoCaptcha token

Example code

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

const auth = app.auth();

// Example: Sign up with phone number verification code or mailbox verification code

Step 1: The user clicks Get Verification Code, use the following method to send the SMS verification code, and store verificationInfo in global for parameter input in step 3.
const phoneNumber = "+86 13800000000";
const verificationInfo = await auth.getVerification({
phone_number: phoneNumber,
});

/*
// If using mailbox verification, change the code in step one to
const email = "test@example.com"
const verificationInfo = await auth.getVerification({
email: email
});
*/

Step 2: Wait for the user to enter the Captcha on the page.
const verificationCode = userInputCode; // 6-digit verification code

Step 3: Verify the Captcha after the user finishes entering the verification code.
await auth.verify({
verification_code: verificationCode,
verification_id: verificationInfo.verification_id,
});

Auth.getVerification()

Note

Get SMS verification code is only supported in the Shanghai region

API description

API feature: get SMS/email verification code

interface declaration: getVerification(params: GetVerificationRequest): Promise<GetVerificationResponse>

API input parameter: GetVerificationRequest

FieldTypeRequiredDescription
phone_numberstringNoMobile number. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx". Choose either this or email.
emailstringNoMailbox. Choose either this or phone_number.
targetTargetNoUsage scenario for mobile number or mailbox
Target
ValueDescription
ANYNo verification of mobile number or mailbox existence. Usage scenario: registration or this kind of logon, not logged in
USERThe mobile number or mailbox must exist in the system and be bound to a user

API output parameter: GetVerificationResponse

FieldTypeDescription
verification_idstringCaptcha ID
is_userbooleanwhether the user is registered

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

API description

API feature: Obtain advanced operation permission through the sudo API, such as change password (Auth.setPassword), change phone number (Auth.bindPhoneNumber), modify email (Auth.bindEmail), delete a user (Auth.deleteMe).

interface declaration: Auth.sudo(params: SudoRequest): Promise<SudoResponse>

API input parameter: SudoRequest

FieldTypeRequiredDescription
passwordstringNoPassword. Choose either password or verification_token. If a mobile number is bound, must use verification_token to perform sudo.
verification_tokenstringNoToken, obtained by verifying the bound mobile number or mailbox by account, which can be retrieved by calling Auth.verify

API output parameter: SudoResponse

FieldTypeDescription
sudo_tokenstringThe advanced privilege token. If the user only enables third-party login and does not set the password, the sudo token is an empty string ""

Example code

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

const auth = app.auth();

// Method one: use password
const pass = "test_password";
const sudoRes = await auth.sudo({
password: pass,
});
console.log(sudoRes.sudo_token);

// Method 2: Obtain via mailbox verification code or phone number verification code.
// The email address or mobile number bound to the current account
const email = "test@example.com";
// const phoneNumber = "+86 13800000000"

Step one: User click to get Captcha, use the following method to send verification code, store verificationInfo in global for step 3 as parameter input.
const verificationInfo = await auth.getVerification({
email: email,
// phone_number: phoneNumber
});

Step 2: Wait for the user to enter the Captcha on the page.
const verificationCode = userInputCode; // 6-digit verification code

Step 3: Verify the Captcha after the user finishes entering the verification code.
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);

// Callable methods: auth.setPassword, auth.bindEmail, auth.bindPhoneNumber, and auth.deleteMe.

Auth.getAccessToken()

API description

API feature: obtain access credential accessToken

interface declaration: Auth.getAccessToken(): Promise<GetAccessTokenResponse>

API input parameter: None

API output parameter: GetAccessTokenResponse

FieldTypeDescription
accessTokenstringAccess token
envstringEnvironment id

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

API description

API feature: Asynchronous operation of Auth.currentUser, returns a User instance representing the current user.

interface declaration: getCurrentUser(): Promise<User | null>

API input parameter: None

API output parameter: User

See User

Example 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 logging in via some method...
const user = await auth.getCurrentUser();

Auth.bindPhoneNumber()

Note

Shanghai region only supported

API description

API feature: bind mobile number

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

API input parameter: BindPhoneRequest

FieldTypeRequiredDescription
phone_numberstringYesNew phone number. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx".
sudo_tokenstringYesThe advanced privilege token, which can be obtained via Auth.sudo.
verification_tokenstringYesThe Captcha token, which can be obtained by calling Auth.verify

API output parameter: None

Example code

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

// Prerequisite, logged in
const auth = app.auth();

Step 1: Obtain sudo token. For details, see the Auth.sudo API.
const sudo_token = "test_sudo_token";

const phone_number = "+86 13800000000";

Step 2: User click Get Verification Code, use the following method to send SMS verification code, and store verificationInfo in global for step 4 as parameter input.
const verificationInfo = await auth.getVerification({
phone_number: phone_number,
});

Step 3: Wait for the user to input the SMS verification code on the page.
const verificationCode = userInputCode; // 6-digit verification code

Step 4: Verify the SMS verification code after the user enters the Captcha.
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 mobile number
await auth.bindPhoneNumber({
phone_number: phone_number,
sudo_token: sudo_token,
verification_token: verification_token,
});

Auth.bindEmail()

API description

API feature: Update email address

interface declaration: bindEmail(params: BindEmailRequest): Promise<void>

API input parameter: BindEmailRequest

FieldTypeRequiredDescription
emailstringyesemail address
sudo_tokenstringYesThe advanced privilege token, which can be obtained via Auth.sudo
verification_tokenstringYesThe verification code token, which can be obtained via Auth.verify

API output parameter: None

Example code

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

// Prerequisite, logged in
const auth = app.auth();


Step 1: Obtain sudo token. For details, see the Auth.sudo API.
const sudoToken = "test_sudo_token"

const newEmail = "new@example.com";

Step 2: User click to get the verification code, use the following method to send the mailbox verification code, and store verificationInfo in global for step 4 as parameter input.
const verificationInfo = await auth.getVerification({
email: newEmail
});

Step 3: Wait for the user to input the SMS verification code on the page.
const verificationCode = userInputCode; // 6-digit verification code

Step 4: Verify the SMS verification code after the user enters the Captcha.
const newEmailTokenRes = await auth.verify({
verification_id: verificationInfo.verification_id,
verification_code: verificationCode,
});
const verificationToken = newEmailTokenRes.verification_token

Step 5: Bind new email.
await auth.bindEmail({
email: newEmail,
sudo_token: sudoToken
verification_token: verificationToken
});

Auth.setPassword()

API description

API feature: set the password (logged in, update user password)

interface declaration: setPassword(params: SetPasswordRequest): Promise<void>

API input parameter: SetPasswordRequest

FieldTypeRequiredDescription
new_passwordstringYesNew password
sudo_tokenstringYesThe advanced privilege token, which can be obtained via Auth.sudo

API output parameter: None

Example 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. For details, see the Auth.sudo API.
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()

API description

API feature: retrieve user information

interface declaration: getUserInfo(): Promise<UserInfo>

API input parameter: None

API output parameter: UserInfo

FieldTypeDescription
namestringUser nickname (case-sensitive from login username)
picturestringUser upload avatar
phone_numberstringUser bound mobile number
email_verifiedbooleanWhether the user has verified the mailbox
birthdatestringUser birthday
localestringLanguage set by the user
zoneinfostringTime zone
UserProfileProviderUserProfileProviderThird-party platform configuration
UserProfileProvider
FieldTypeRequiredDescription
idstringNoDefault built-in third-party provider_id, such as wx_open, wx_mp
provider_user_idstringNoThird-party provider user ID (such as wxopenid)
namestringNoName
System built-in third-party list
provider_idMeaning
wx_openWeixin Open Platform
wx_mpWeChat official account

google google platform

Example 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 scenario and anonymous login scenario do not support using this API to query user information (Please query user information manually in business service for custom login scenario. Anonymous login scenario is not supported).

API description

API feature: query user by any parameter: userName, mailbox, or mobile number.

interface declaration: queryUser(queryObj: QueryUserProfileRequest): Promise<QueryUserProfileResponse>;

API input parameter: QueryUserProfileRequest

FieldTypeRequiredDescription
idArray<string>NoUser uid array, supports querying up to 50 ids
usernamestringNoUsername
emailstringNoMailbox
phone_numberstringNoMobile number. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx".

API output parameter: QueryUserProfileResponse

FieldTypeRequiredDescription
totalstringNoQuantity
dataSimpleUserProfile[]NoList of users
SimpleUserProfile
FieldTypeRequiredDescription
substringYesIndex
namestringYesName
picturestringNoImage
genderstringNoGender
localestringNoLocation
emailstringNoMailbox
phone_numberstringNoMobile number

Example 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

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

API description

API feature: reset the password (when a user forgets the password and is unable to log in, use this API to force setting the password)

interface declaration: resetPassword(params: ResetPasswordRequest): Promise<void>

API input parameter: ResetPasswordRequest

FieldTypeRequiredDescription
emailstringNoMailbox. Choose either this or phone_number.
phone_numberstringNoMobile number. Choose either this or email. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx".
new_passwordstringYesNew password
verification_tokenstringYesThe verification code token, which can be obtained via Auth.verify

API output parameter: None

Example 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 click Get Verification Code, use the following method to send SMS verification code, and store verificationInfo in global for step 3 as parameter input.
const verificationInfo = await auth.getVerification({
phone_number: phoneNumber,
});

Step 2: Wait for the user to manually input the SMS verification code on the page.
const verificationCode = userInputCode; // 6-digit verification code

Step 3: Verify the SMS verification code after the user enters the Captcha.
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()

API description

API feature: check username existence.

interface declaration: isUsernameRegistered(username: string): Promise<boolean>

API input parameter

FieldTypeRequiredDescription
usernamestringYesUsername, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed

API output parameter: boolean

ValueDescription
trueexists
falseDoes not exist

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

API description

API feature: delete a user.

interface declaration: deleteMe(params: WithSudoRequest): Promise<UserProfile>

API input parameter: WithSudoRequest

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

API output parameter: UserProfile

FieldTypeDescription
substringUnique user ID
namestringUser nickname (case-sensitive from login username)
usernamestringUsername, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed
picturestringUser upload avatar
phone_numberstringUser bound mobile number
emailstringUser bound mailbox
email_verifiedbooleanWhether the user has verified the mailbox
groupsArray<{id: string; expires_at?: string}>User group/role list (array of strings)
genderstringGender
birthdatestringUser birthday
localestringLanguage set by the user
zoneinfostringTime zone
providersArray<UserProfileProvider>Third-party platform configuration

Example 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 by performing sudo operations. For details, see the Auth.sudo method.

// 2. deleteMe

const user = await auth.deleteMe({
sudo_token: "your sudo_token",
});

Auth.loginScope()

API description

API feature: Query user permissions to determine whether it is an anonymous login status.

interface declaration: loginScope(): Promise<string>

API input parameter: None

API output parameter: string

Example 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 a method...

const loginScope = await auth.loginScope();
if (loginScope === "anonymous") {
console.log("currently anonymous login method");
}

LoginState

LoginState object is an abstraction of users' current logon status

Auth.hasLoginState()

API description

API feature: Return current log-in status LoginState. If not logged in, return null.

interface declaration: hasLoginState(): LoginState | null

API input parameter: None

API output parameter: LoginState

See LoginState. Return null means not logged in.

Example 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 state valid
} else {
// Not logged in, or login state has expired
}

Auth.getLoginState()

API description

API feature: Asynchronous operation of Auth.hasLoginState(), return current log-in status LoginState. Return null means that not logged in.

interface declaration: getLoginState(): Promise<LoginState | null>

Note

This API is the async mode of hasLoginState, suitable for platforms with asynchronous local storage, such as React Native.

API input parameter: None

API output parameter: LoginState

See LoginState. Return null means not logged in.

Example 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 state valid
} else {
// Not logged in, or login state has expired
}

Auth.onLoginStateChanged()

API description

API feature: Listen to login status changes. The function will be triggered when the login status changes, such as calling registration/login/logout related APIs or Credentials exceptions (for example, 'credentials not found', 'no refresh token found in credentials' errors).

interface declaration: onLoginStateChanged(callback: Function): Promise<void>

API input parameter: OnLoginStateChangedParams

FieldTypeRequiredDescription
callbackFunctionYesCallback function
callback function input parameter definition
FieldTypeDescription
namestringDefault value: loginStateChanged
dataobjectinclude { msg?: string; eventType: 'sign_in'
Note

If eventType is sign_in or sign_out, current log-in status LoginState will be returned.

API output parameter: None

Example 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 is successful
break;
case "sign_out":
// Logout is successful
break;
case "credentials_error":
// Permission expired
break;
default:
return;
}
});

LoginState.user

Type: User | null

Refers to the current user, reference User

If not logged in, the value is null.

User

User.update()

API description

API feature: update user information

interface declaration: update(userInfo): Promise<void>

API input parameter: userInfo

FieldTypeRequiredDescription
namestringNoUser nickname (case-sensitive from login username)
usernamestringNoUsername, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed
picturestringNoUser upload avatar
phone_numberstringNoUser bound mobile number
emailstringNoUser bound email
genderstringNoGender, value limited to MALE, FEMALE, UNKNOWN
birthdatestringNoUser birthday

API output parameter: None

Example code

const user = auth.currentUser;

user
.update({
gender: "MALE", // Gender, value limited to MALE, FEMALE, UNKNOWN
})
.then(() => {
// User information is updated successfully.
});

User.refresh()

API description

API feature: refresh local user information. After the user updates user information on other clients, call this API to synchronize the updated info.

interface declaration: refresh(): Promise<UserInfo>

API input parameter: None

API output parameter: UserInfo

FieldTypeDescription
substringUnique user ID
namestringUser nickname (case-sensitive from login username)
usernamestringUsername, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed
picturestringUser upload avatar
phone_numberstringUser bound mobile number
emailstringUser bound email
email_verifiedbooleanWhether the user has verified the mailbox
groupsArray<{id: string; expires_at?: string}>User group/role list (array of strings)
genderstringGender
birthdatestringUser birthday
localestringLanguage set by the user
zoneinfostringTime zone
providersArray<UserProfileProvider>Third-party platform configuration

Example code

const user = auth.currentUser;

user.refresh().then((userInfo) => {
// User information is updated successfully.
});

Error Code

Login error

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

Registration error

Error CodeDescription
failed_preconditionThe phone number or mailbox you input is already registered, please use another number
Error CodeDescription
failed_preconditionFailed to obtain user information from a third party
resource_exhaustedToo frequent attempts, please retry later
invalid_argumentThe input verification code is incorrect or expired
abortedToo many attempts, please go back to the first page and try again later
permission_deniedYour current session has expired, please return and retry
captcha_requiredCaptcha is required to connect to the anti-robot service
captcha_invalidIncorrect Captcha, required to connect to the anti-robot service

Other Errors

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

Error Description

Error CodeError DescriptionDescription
permission_deniedcors permission denied, please check if {url} is in your client {env} domainsPlease check whether the secure domain name {url} has been configured in the corresponding {env} environment under "Cloud Development Platform - Environment Settings - Secure Source - Protected Domains". It will take effect 10 minutes after configuration.

error==captcha_required or error==captcha_invalid means the request triggers Captcha-related logic. Machine verification is required.

After the Captcha process is completed, if the business API returns error equal to captcha_required, it means the request requires the captcha_token parameter. Use the local unexpired verification code if possible. When error equals captcha_invalid, it means the verification code is invalid and you need to reobtain it. In the same verification process, captcha_invalid can only be attempted once.

If you need to use the adapter to process, refer to the Captcha handling 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) Domain names or IP addresses upon Captcha verification completion. state: (Required) A system status string, which will carry the state after Captcha verification is completed.

Response 1: Status code 200 and the url field is not empty, display required verification code and complete the verification.

If the user requests too frequently or there is other risk, the verification code service will be returned in the form below.

{
"url": "https://exmaple.com/captcha.html",
"expires_in": 600
}

At this point, user behavior requires verification code verification to proceed. Once the request succeeds, the client opens the url through a browser or webview/iframe, such as the above https://exmaple.com/captcha.html. Once processing is complete in the web, it will auto-redirect to the following address (where captcha_token is the verification code 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 must listen for adjustments to the redirect_uri address. When the address is appanme://com.package.name/callback, compare whether the state is identical to the one passed in, and obtain captcha_token and expires_in.

If an error occurs during the verification process, the validation page will show error information. When you return after a user click, the validation page will redirect with the error and error_description appended to the redirect_uri, for example:

https://example.com/callback?state=xxxxx&error=xxx&error_description=xxx

At this point, the business side can restore the Home Page as needed or handle other issues.

Response 2: Status code is not 200, need to handle the error

If the user requests too frequently or there is other risk, the verification code service will be returned in the form below.

{
"error": "resource_exhausted",
"error_description": "Your operation is too frequent, please try again later"
}

At this point, the client needs to show error_description and can combine with i18n to display multilingual content.

Get captcha_token and request again

Get captcha_token and place it into the url parameter to handle request.

For example, requesting /v1/example returns a captcha_invalid error. At this point, request /v1/example?captcha_token=hbGciOiJeyJhbGciOiJSUAeyJhbGciOiJ again and click OK to complete.

Type definition

User

User object is an abstraction of current user information

PropertyTypeDescription
uidstring | undefinedUnique user ID
genderstring | undefinedGender
picturestring | undefinedProfile photo URL
emailstring | undefinedMailbox
emailVerifiedboolean | undefinedWhether the mailbox is verified
phoneNumberstring | undefinedMobile number
usernamestring | undefinedUsername, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed
namestring | undefinedUser nickname
providersArray<{ id?: string; providerUserId?: string; name?: string }> | undefinedThird-party login bound list
birthdatestring | undefinedDate of birth
substring | undefinedSubject ID (JWT sub)

Credentials

Credentials object defines the credential information structure for identity verification and authorization

PropertyTypeDescription
token_typestring | nullToken type, common value is Bearer, used to indicate the authentication scheme of the token
access_tokenstring | nullAccess token, used for calling protected resources as identity credential
refresh_tokenstring | nullRefresh token, used to get a new access token after expiry
scopestring | nullPermission scope, typically separated by spaces (for example "openid profile email")
expires_innumber | nullAccess token valid period, in seconds
expires_atDate | nullAccess token expiration time point
substring | nullUnique user ID
groupsstring[] | nullUser group/role list (string array)
versionstringVersion number or source flag of the credential

LoginState

LoginState object is an abstraction of users' current logon status

PropertyTypeDescription
userUserUser Object
oauthLoginStateCredentials | nullCredentials Object