authentication
Identity Verification
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
@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
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
| Field | Type | Required | Description |
|---|---|---|---|
| phone_number | string | No | Mobile number used for registration. You must choose either phone_number or email. |
| string | No | Mailbox used for registration. You must choose either phone_number or email. | |
| verification_code | string | No | Verification code, which can be obtained by calling Auth.getVerification |
| verification_token | string | No | Captcha token, which can be obtained by calling Auth.verify |
| provider_token | string | No | Third-party provider token, used to bind third-party user info, which can be obtained via Auth.grantProviderToken |
| password | string | No | Password |
| name | string | No | Username |
| gender | string | No | Gender |
| picture | string | No | Avatar |
| locale | string | No | Address |
| username | string | No | Username, 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()
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
| Field | Type | Required | Description |
|---|---|---|---|
| username | string | Yes | User mobile number, mailbox or custom username. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx". |
| password | string | No | User password. Choose either password or verification_token. |
| verification_token | string | No | Captcha 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
| Field | Type | Required | Description |
|---|---|---|---|
| redirect_uri | string | No | The redirect page host address after exiting |
| state | string | No | When 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
| Field | Type | Description |
|---|---|---|
| redirect_uri | string | The 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
| Field | Type | Description |
|---|---|---|
| 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()
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
| Field | Type | Required | Default Value | Description |
|---|---|---|---|---|
| useWxCloud | boolean | No | true | true: 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()
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()
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
| field | data type | required | default value | description |
|---|---|---|---|---|
| phoneCode | string | yes | empty | WeChat 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()
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
| Field | Type | Required | Default Value | Description |
|---|---|---|---|---|
| verificationInfo | object | Captcha token information | {} | Returned value of Auth.getVerification |
| verificationCode | string | verification code | empty | Obtained SMS verification code. A verification code will be sent after calling Auth.getVerification |
| phoneNum | string | Mobile number | Empty | The 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
| Field | Type | Required | Default Value | Description |
|---|---|---|---|---|
| verificationInfo | object | Captcha token information | {} | Returned value of Auth.getVerification |
| verificationCode | string | verification code | empty | Obtained mailbox verification code. A verification code will be sent after calling Auth.getVerification |
| string | mailbox | empty | email 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()
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
| Field | Type | Meaning | Default Value | Description |
|---|---|---|---|---|
| config_version | string | Login configuration version of the default login page | env | 1. '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_uri | string | Redirection address after login | Defaults to current page address | |
| app_id | string | application id | empty | required item when config_version is not 'env', for example app-xxx |
| query | object | Parameters to carry when navigating to the default login page | empty |
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
| Field | Type | Required | Description |
|---|---|---|---|
| provider_id | string | Yes | Third-party platform ID, see system built-in third-party platform list |
| provider_redirect_uri | string | Yes | The third-party platform redirection uri. After authorization is completed, the url will carry the code parameter during redirection. |
| state | string | Yes | User-defined status identifier field to identify third-party platform callback source |
| other_params | {sign_out_uri?:string} | No | Other parameters |
API output parameter: GenProviderRedirectUriResponse
| Field | Type | Required | Description |
|---|---|---|---|
| uri | string | Yes | Client request |
| signout_uri | string | Yes | Logout 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
| Field | Type | Required | Description |
|---|---|---|---|
| provider_id | string | Yes | Third-party platform ID, see system built-in third-party list |
| provider_redirect_uri | string | No | Third-party platform redirect uri |
| provider_code | string | No | Third-party platform authorization code (carried in redirect uri) |
| provider_access_token | string | No | Third-party platform access token (carried in redirect uri) |
| provider_id_token | string | No | Third-party platform ID token (carried in redirect uri) |
API output parameter: GrantProviderTokenResponse
| Field | Type | Required | Description |
|---|---|---|---|
| provider_token | string | Yes | Third-party platform token |
| expires_in | number | Required | Valid period |
| provider_profile | ProviderProfile | No | Third-party identity source info |
ProviderProfile
| Field | Type | Required | Description |
|---|---|---|---|
| provider_id | string | Required | Default built-in third-party providerid, wx_open, wx_mp |
| sub | string | Yes | Third-party user id (such as wxopenid) |
| name | string | No | Name |
| phone_number | string | No | Mobile number |
| picture | string | No | Avatar |
| meta | ProviderProfileMeta | No | Extended information of third-party identity source (returned by mini program) |
ProviderProfileMeta
| Field | Type | Required | Description |
|---|---|---|---|
| appid | string | No | Mini program appid |
| openid | string | No | Mini 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
| Field | Type | Required | Description |
|---|---|---|---|
| provider_token | string | Yes | Third-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
| Field | Type | Required | Description |
|---|---|---|---|
| provider_id | string | Yes | Third-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
| Field | Type | Required | Description |
|---|---|---|---|
| id | string | Yes | Third-party platform ID |
| provider_user_id | string | Yes | Third-party platform user ID |
| name | string | Yes | Third-party platform Nickname |
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
| Field | Type | Required | Description |
|---|---|---|---|
| provider_token | string | Yes | The 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,
});
Verify/Authorization Related
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
| Field | Type | Required | Description |
|---|---|---|---|
| token | string | Yes | Captcha token, obtained from the URL parameter in the captchaOptions.openURIWithCallback callback of the adapter |
| key | string | Yes | The answer to the graphic verification code in user input |
API output parameter: CaptchaToken
| Field | Type | Description |
|---|---|---|
| captcha_token | string | The verify token returned after verification passes |
| expires_in | number | Token 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;
},
},
};
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:
- Parse parameters such as
captcha_data(verification code image) andtokenfrom the callback URL. - Display the verification code image to users
- Retrieve the user-entered Captcha answer
- Call the
verifyCaptchaDataAPI to validate and obtaincaptchaToken - Return
captchaTokenas 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
| Field | Type | Required | Description |
|---|---|---|---|
| verification_code | string | Yes | Verification code, which can be obtained by calling Auth.getVerification |
| verification_id | string | Yes | Captcha ID, which can be obtained by calling Auth.getVerification |
API output parameter: VerifyResponse
| Field | Type | Required | Description |
|---|---|---|---|
| verification_token | string | No | Captcha 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()
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
| Field | Type | Required | Description |
|---|---|---|---|
| phone_number | string | No | Mobile number. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx". Choose either this or email. |
| string | No | Mailbox. Choose either this or phone_number. | |
| target | Target | No | Usage scenario for mobile number or mailbox |
Target
| Value | Description |
|---|---|
| ANY | No verification of mobile number or mailbox existence. Usage scenario: registration or this kind of logon, not logged in |
| USER | The mobile number or mailbox must exist in the system and be bound to a user |
API output parameter: GetVerificationResponse
| Field | Type | Description |
|---|---|---|
| verification_id | string | Captcha ID |
| is_user | boolean | whether 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
| Field | Type | Required | Description |
|---|---|---|---|
| password | string | No | Password. Choose either password or verification_token. If a mobile number is bound, must use verification_token to perform sudo. |
| verification_token | string | No | Token, obtained by verifying the bound mobile number or mailbox by account, which can be retrieved by calling Auth.verify |
API output parameter: SudoResponse
| Field | Type | Description |
|---|---|---|
| sudo_token | string | The 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
| Field | Type | Description |
|---|---|---|
| accessToken | string | Access token |
| env | string | Environment 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);
User Information Related
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()
Shanghai region only supported
API description
API feature: bind mobile number
interface declaration: bindPhoneNumber(params: BindPhoneRequest): Promise<void>
API input parameter: BindPhoneRequest
| Field | Type | Required | Description |
|---|---|---|---|
| phone_number | string | Yes | New phone number. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx". |
| sudo_token | string | Yes | The advanced privilege token, which can be obtained via Auth.sudo. |
| verification_token | string | Yes | The 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
| Field | Type | Required | Description |
|---|---|---|---|
| string | yes | email address | |
| sudo_token | string | Yes | The advanced privilege token, which can be obtained via Auth.sudo |
| verification_token | string | Yes | The 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
| Field | Type | Required | Description |
|---|---|---|---|
| new_password | string | Yes | New password |
| sudo_token | string | Yes | The 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
| Field | Type | Description |
|---|---|---|
| name | string | User nickname (case-sensitive from login username) |
| picture | string | User upload avatar |
| phone_number | string | User bound mobile number |
| email_verified | boolean | Whether the user has verified the mailbox |
| birthdate | string | User birthday |
| locale | string | Language set by the user |
| zoneinfo | string | Time zone |
| UserProfileProvider | UserProfileProvider | Third-party platform configuration |
UserProfileProvider
| Field | Type | Required | Description |
|---|---|---|---|
| id | string | No | Default built-in third-party provider_id, such as wx_open, wx_mp |
| provider_user_id | string | No | Third-party provider user ID (such as wxopenid) |
| name | string | No | Name |
System built-in third-party list
| provider_id | Meaning |
|---|---|
| wx_open | Weixin Open Platform |
| wx_mp | WeChat 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()
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
| Field | Type | Required | Description |
|---|---|---|---|
| id | Array<string> | No | User uid array, supports querying up to 50 ids |
| username | string | No | Username |
| string | No | Mailbox | |
| phone_number | string | No | Mobile number. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx". |
API output parameter: QueryUserProfileResponse
| Field | Type | Required | Description |
|---|---|---|---|
| total | string | No | Quantity |
| data | SimpleUserProfile[] | No | List of users |
SimpleUserProfile
| Field | Type | Required | Description |
|---|---|---|---|
| sub | string | Yes | Index |
| name | string | Yes | Name |
| picture | string | No | Image |
| gender | string | No | Gender |
| locale | string | No | Location |
| string | No | Mailbox | |
| phone_number | string | No | Mobile 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()
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
| Field | Type | Required | Description |
|---|---|---|---|
| string | No | Mailbox. Choose either this or phone_number. | |
| phone_number | string | No | Mobile number. Choose either this or email. For China mobile numbers, include the country code "+86", for example "+86 138xxxxxxxxx". |
| new_password | string | Yes | New password |
| verification_token | string | Yes | The 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
| Field | Type | Required | Description |
|---|---|---|---|
| username | string | Yes | Username, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed |
API output parameter: boolean
| Value | Description |
|---|---|
| true | exists |
| false | Does 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
| Field | Type | Required | Description |
|---|---|---|---|
| sudo_token | string | Yes | The advanced privilege token, which can be obtained via Auth.sudo |
API output parameter: UserProfile
| Field | Type | Description |
|---|---|---|
| sub | string | Unique user ID |
| name | string | User nickname (case-sensitive from login username) |
| username | string | Username, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed |
| picture | string | User upload avatar |
| phone_number | string | User bound mobile number |
| string | User bound mailbox | |
| email_verified | boolean | Whether the user has verified the mailbox |
| groups | Array<{id: string; expires_at?: string}> | User group/role list (array of strings) |
| gender | string | Gender |
| birthdate | string | User birthday |
| locale | string | Language set by the user |
| zoneinfo | string | Time zone |
| providers | Array<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>
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
| Field | Type | Required | Description |
|---|---|---|---|
| callback | Function | Yes | Callback function |
callback function input parameter definition
| Field | Type | Description |
|---|---|---|
| name | string | Default value: loginStateChanged |
| data | object | include { msg?: string; eventType: 'sign_in' |
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
| Field | Type | Required | Description |
|---|---|---|---|
| name | string | No | User nickname (case-sensitive from login username) |
| username | string | No | Username, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed |
| picture | string | No | User upload avatar |
| phone_number | string | No | User bound mobile number |
| string | No | User bound email | |
| gender | string | No | Gender, value limited to MALE, FEMALE, UNKNOWN |
| birthdate | string | No | User 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
| Field | Type | Description |
|---|---|---|
| sub | string | Unique user ID |
| name | string | User nickname (case-sensitive from login username) |
| username | string | Username, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed |
| picture | string | User upload avatar |
| phone_number | string | User bound mobile number |
| string | User bound email | |
| email_verified | boolean | Whether the user has verified the mailbox |
| groups | Array<{id: string; expires_at?: string}> | User group/role list (array of strings) |
| gender | string | Gender |
| birthdate | string | User birthday |
| locale | string | Language set by the user |
| zoneinfo | string | Time zone |
| providers | Array<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 Code | Description |
|---|---|
| not_found | User does not exist |
| password_not_set | The current user has not set a password, please use Captcha or third-party login method |
| invalid_password | Incorrect Password |
| user_pending | User not activated |
| user_blocked | User disabled |
| invalid_status | Exceeds the maximum number of retries for password, try again later |
| invalid_two_factor | MFA code mismatched or outdated |
Registration error
| Error Code | Description |
|---|---|
| failed_precondition | The phone number or mailbox you input is already registered, please use another number |
Captcha-related errors
| Error Code | Description |
|---|---|
| failed_precondition | Failed to obtain user information from a third party |
| resource_exhausted | Too frequent attempts, please retry later |
| invalid_argument | The input verification code is incorrect or expired |
| aborted | Too many attempts, please go back to the first page and try again later |
| permission_denied | Your current session has expired, please return and retry |
| captcha_required | Captcha is required to connect to the anti-robot service |
| captcha_invalid | Incorrect Captcha, required to connect to the anti-robot service |
Other Errors
| Error Code | Description |
|---|---|
| unreachable | Network error. Check your network connection and try again later |
Error Description
| Error Code | Error Description | Description |
|---|---|---|
| permission_denied | cors permission denied, please check if {url} is in your client {env} domains | Please 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. |
Captcha-related handling
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
| Property | Type | Description |
|---|---|---|
| uid | string | undefined | Unique user ID |
| gender | string | undefined | Gender |
| picture | string | undefined | Profile photo URL |
| string | undefined | Mailbox | |
| emailVerified | boolean | undefined | Whether the mailbox is verified |
| phoneNumber | string | undefined | Mobile number |
| username | string | undefined | Username, length 5-24 characters, supports Chinese and English characters, digits, special characters (only _-), Chinese characters are not allowed |
| name | string | undefined | User nickname |
| providers | Array<{ id?: string; providerUserId?: string; name?: string }> | undefined | Third-party login bound list |
| birthdate | string | undefined | Date of birth |
| sub | string | undefined | Subject ID (JWT sub) |
Credentials
Credentials object defines the credential information structure for identity verification and authorization
| Property | Type | Description |
|---|---|---|
| token_type | string | null | Token type, common value is Bearer, used to indicate the authentication scheme of the token |
| access_token | string | null | Access token, used for calling protected resources as identity credential |
| refresh_token | string | null | Refresh token, used to get a new access token after expiry |
| scope | string | null | Permission scope, typically separated by spaces (for example "openid profile email") |
| expires_in | number | null | Access token valid period, in seconds |
| expires_at | Date | null | Access token expiration time point |
| sub | string | null | Unique user ID |
| groups | string[] | null | User group/role list (string array) |
| version | string | Version number or source flag of the credential |
LoginState
LoginState object is an abstraction of users' current logon status
| Property | Type | Description |
|---|---|---|
| user | User | User Object |
| oauthLoginState | Credentials | null | Credentials Object |