Skip to main content

Login Configuration

getLoginConfig

1. API Description

API feature: Query login policy configuration

API declaration: app.env.getLoginConfig(): Promise<Object>

version tip

This API has been supported since v5.1.0.

Queries the login policy configuration of the specified TCB environment, including the enable status of phone number SMS login, email login, username-password login, and anonymous login, as well as SMS verification code sending channel, MFA multi-factor authentication, and password update policy.

2. Input Parameters

N/A

3. Return Results

FieldRequiredTypeDescription
RequestIdYesStringUnique identifier of the request
EmailLoginYesBooleanWhether email login is enabled
AnonymousLoginYesBooleanWhether anonymous login is enabled
UserNameLoginYesBooleanWhether username-password login is enabled
PhoneNumberLoginYesBooleanWhether phone number SMS login is enabled
SmsVerificationConfigYesSmsVerificationConfigSMS verification code sending configuration, see below
MfaConfigNoMfaConfigMFA multi-factor authentication login configuration
PwdUpdateStrategyNoPwdUpdateStrategyPassword update policy configuration

SmsVerificationConfig

FieldRequiredTypeDescription
TypeNoStringSMS sending channel type, e.g. default
NameNoStringCustom APIs data source name
MethodNoStringInvocation method
SmsDayLimitNoNumberDaily sending limit, -1 means unlimited

MfaConfig

FieldRequiredTypeDescription
OnNoStringMFA factor authentication, TRUE or FALSE
SmsNoStringSMS verification, TRUE or FALSE
EmailNoStringEmail verification, TRUE or FALSE
RequiredBindPhoneNoStringMandatory phone number binding, TRUE or FALSE

PwdUpdateStrategy

FieldRequiredTypeDescription
FirstLoginUpdateNoBooleanWhether to force password change on first login
PeriodUpdateNoBooleanWhether to enable periodic forced password change
PeriodValueNoNumberPeriod value for periodic password change
PeriodTypeNoStringPeriod time unit, e.g. YEAR, MONTH, WEEK

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
const res = await app.env.getLoginConfig()
console.log('Email login:', res.EmailLogin)
console.log('Anonymous login:', res.AnonymousLogin)
console.log('Username-password login:', res.UserNameLogin)
console.log('Phone number SMS login:', res.PhoneNumberLogin)
}

test()

modifyLoginConfig

1. API Description

API feature: Modify login policy configuration

API declaration: app.env.modifyLoginConfig(params): Promise<Object>

version tip

This API has been supported since v5.1.0.

Modifies the login policy configuration of the specified TCB environment. Supports enabling or disabling phone number SMS login, email login, username-password login, and anonymous login. Also allows configuring SMS verification code sending channel, MFA multi-factor authentication, and password update policy. Changes take effect immediately and affect the login behavior of all end users under the environment.

2. Input Parameters

FieldRequiredTypeDescription
PhoneNumberLoginYesBooleanPhone number SMS login switch
EmailLoginYesBooleanEmail login switch
UserNameLoginYesBooleanUsername-password login switch
AnonymousLoginYesBooleanAnonymous login switch
SmsVerificationConfigNoObjectSMS verification code sending configuration. If not passed, the current configuration will not be modified. See SmsVerificationConfig
MfaConfigNoObjectMFA multi-factor authentication login configuration. If not passed, the current configuration will not be modified. See MfaConfig
PwdUpdateStrategyNoObjectPassword update policy configuration. If not passed, the current configuration will not be modified. See PwdUpdateStrategy

3. Return Results

FieldTypeDescription
RequestIdStringUnique identifier of the request

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
// First, query the current configuration
const config = await app.env.getLoginConfig()

// Enable anonymous login
const res = await app.env.modifyLoginConfig({
PhoneNumberLogin: config.PhoneNumberLogin,
EmailLogin: config.EmailLogin,
UserNameLogin: config.UserNameLogin,
AnonymousLogin: true
})
console.log(res.RequestId)
}

test()

describeClient

1. API Description

API feature: Query application client details

API declaration: app.env.describeClient(id): Promise<Object>

version tip

This API has been supported since v5.1.0.

Retrieves the configuration of a specific client under the specified TCB environment, including OAuth credentials, token validity period, session control policy, etc. When the client ID equals the environment ID, the default client configuration for that environment is returned.

2. Input Parameters

FieldRequiredTypeDescription
IdYesStringClient unique identifier (Client ID), typically uses the environment ID

3. Return Results

FieldRequiredTypeDescription
RequestIdYesStringUnique identifier of the request
IdYesStringClient unique identifier (Client ID)
CreatedAtNoStringClient creation time, ISO 8601 format
UpdatedAtNoStringClient last modification time, ISO 8601 format
RefreshTokenExpiresInNoNumberRefresh Token validity period in seconds
AccessTokenExpiresInNoNumberAccess Token validity period in seconds
MaxDeviceNoNumberMaximum number of concurrent sessions per user, -1 means unlimited

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
const res = await app.env.describeClient('your-env-id')
console.log('Client ID:', res.Id)
console.log('Refresh Token validity:', res.RefreshTokenExpiresIn, 'seconds')
console.log('Access Token validity:', res.AccessTokenExpiresIn, 'seconds')
console.log('Max sessions:', res.MaxDevice)
}

test()

modifyClient

1. API Description

API feature: Modify application client configuration

API declaration: app.env.modifyClient(params): Promise<Object>

version tip

This API has been supported since v5.1.0.

Uses an incremental update strategy, only updating non-empty fields passed in the request. Fields not included remain unchanged. Supports modifying token validity period, session control policy, and other configurations. When the client ID equals the environment ID and the client has not been created yet, a default client configuration will be automatically created.

2. Input Parameters

FieldRequiredTypeDescription
IdYesStringClient unique identifier (Client ID)
RefreshTokenExpiresInNoNumberRefresh Token validity period in seconds, range 1800~2592000, default 2592000
AccessTokenExpiresInNoNumberAccess Token validity period in seconds, minimum 1800, default 7200, should be less than RefreshTokenExpiresIn
MaxDeviceNoNumberMaximum number of concurrent sessions per user. -1 for unlimited, 0 for User-Agent based differentiation, 1~50 for precise limit

3. Return Results

FieldTypeDescription
RequestIdStringUnique identifier of the request

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
const res = await app.env.modifyClient({
Id: 'your-env-id',
RefreshTokenExpiresIn: 2592000,
AccessTokenExpiresIn: 7200,
MaxDevice: 5
})
console.log(res.RequestId)
}

test()

getProviders

1. API Description

API feature: Get the list of third-party authentication sources

API declaration: app.env.getProviders(): Promise<Object>

version tip

This API has been supported since v5.1.0.

Queries the list of identity authentication sources under the specified TCB environment, including third-party login (OAuth, OIDC, SAML), WeChat Mini Program login, custom login, and email login. If a custom login or email login identity source has not been created, the API will automatically append a default disabled record.

2. Input Parameters

N/A

3. Return Results

FieldRequiredTypeDescription
RequestIdYesStringUnique identifier of the request
TotalNoNumberTotal number of authentication sources
DataNoArray<Provider>List of third-party authentication sources

Provider

FieldRequiredTypeDescription
IdYesStringIdentity source unique identifier, 2-32 lowercase letters and digits
ConfigYesObjectIdentity source security authentication configuration, see ProviderConfig
NameNoLocalizedMessageIdentity source name, supports internationalized multi-language configuration
PictureNoStringIdentity source icon URL
HomepageNoStringIdentity source official homepage URL
ProviderTypeNoStringIdentity source protocol type: OAUTH, OIDC, SAML, CUSTOM, EMAIL, etc.
OnNoStringIdentity source enable status, TRUE or FALSE
AutoSignUpWithProviderUserNoStringWhether to automatically register system users, TRUE, FALSE, UNSPECIFIED
TransparentModeNoStringWhether to enable transparent mode, TRUE or FALSE
ReuseUserIdNoStringWhether to reuse third-party user ID, TRUE or FALSE
EmailConfigNoEmailConfigEmail identity source specific configuration, only valid when ProviderType is EMAIL
DescriptionNoLocalizedMessageIdentity source description, supports internationalized multi-language configuration
AutoSignInWhenEmailMatchNoStringWhether to enable automatic email-based login association, TRUE, FALSE, UNSPECIFIED
AutoSignInWhenPhoneNumberMatchNoStringWhether to enable automatic phone number-based login association, TRUE, FALSE, UNSPECIFIED

ProviderConfig

FieldTypeRequiredDescription
IssuerStringRecommended for OIDCUnique identifier of the identity provider (Issuer URL), used to verify the iss field in the ID Token. Only required when ProviderType is OIDC. The value is typically the root URL of the third-party OIDC service, e.g. https://accounts.google.com. Once provided, the platform will automatically discover and populate endpoint addresses such as AuthorizationEndpoint, TokenEndpoint, UserinfoEndpoint, and JwksUri via /.well-known/openid-configuration
JwksUriStringRequired for OIDCJSON Web Key Set URL, used to obtain public keys for verifying ID Token signatures. Only required when ProviderType is OIDC. If Issuer is already provided, this field will be auto-populated via Discovery
ClientIdStringRequired for OIDC/OAUTHApplication client ID registered with the third-party identity provider. Required when ProviderType is OIDC or OAUTH, obtainable from the corresponding platform's developer console
ClientSecretStringRequired for OIDC/OAUTHApplication client secret registered with the third-party identity provider, used in conjunction with ClientId for authentication at the Token endpoint. Required when ProviderType is OIDC or OAUTH. Keep it secure to prevent leakage
RedirectUriStringRequired for OIDC/OAUTHCallback URL after OAuth authorization is completed. Must exactly match the callback URL registered on the third-party platform. Required when ProviderType is OIDC or OAUTH. Example: https://envId.ap-shanghai.tcb-api.tencentcloudapi.com/auth/v1/callback
ScopeStringRequired for OIDC/OAUTHPermission scope requested from the third party, multiple scopes separated by spaces. Required when ProviderType is OIDC or OAUTH. For OIDC scenarios, at least openid should be included; append email, phone, etc. for additional information. If Issuer is provided and Scope is not specified, the scopes_supported from Discovery will be used automatically. Example: openid email name
AuthorizationEndpointStringRequired for OIDC/OAUTHAuthorization endpoint URL, used to redirect users to the third-party login page. Required when ProviderType is OIDC or OAUTH. If Issuer is provided, this field will be auto-populated via Discovery
TokenEndpointStringRequired for OIDC/OAUTHToken endpoint URL, used to exchange authorization code for Access Token and ID Token. Required when ProviderType is OIDC or OAUTH. If Issuer is provided, this field will be auto-populated via Discovery
UserinfoEndpointStringAs needed for OIDC/OAUTHUserinfo endpoint URL, used to obtain basic user information (nickname, avatar, email, etc.) via Access Token. Required when ProviderType is OIDC or OAUTH and detailed user information is needed. If Issuer is provided, this field will be auto-populated via Discovery
ResponseTypeStringNoResponse type for the authorization request. Options: code (authorization code flow, recommended), token (implicit flow), id_token (direct ID Token return). Default is id_token for OIDC ProviderType, code for other types
SignoutEndpointStringNoSingle sign-out endpoint URL. When configured, the user will be redirected to this URL on logout to invalidate the third-party IDP session. If not provided, only the platform session will be cleared on logout
TokenEndpointAuthMethodStringNoClient authentication method at the Token endpoint. Options: CLIENT_SECRET_POST (credentials in request body), CLIENT_SECRET_BASIC (credentials via HTTP Basic Auth Header). Default is CLIENT_SECRET_POST
SamlMetadataStringRequired for SAMLSAML identity provider Metadata XML content, including entity ID, SSO endpoint URL, signing certificate, etc. Maximum 10KB. Only required when ProviderType is SAML, typically downloadable from the third-party IDP management console
RequestParametersMapRequestParametersMapNoRequest parameter mapping configuration for handling non-standard OAuth protocol parameter transformations. By default, strictly follows the OAuth 2.0 standard. Configuration is needed when integrating with non-standard platforms such as WeChat or WeCom
ResponseParametersMapResponseParametersMapNoResponse parameter mapping configuration for handling non-standard OAuth protocol response parameter transformations. When integrating with non-standard platforms such as WeChat, third-party returned fields can be mapped to platform standard fields
Required Fields Summary
  • OIDC type: It is recommended to provide Issuer (auto-discovery of endpoints), or manually provide ClientId, ClientSecret, RedirectUri, Scope, AuthorizationEndpoint, TokenEndpoint, JwksUri
  • OAUTH type: Required fields are ClientId, ClientSecret, RedirectUri, Scope, AuthorizationEndpoint, TokenEndpoint
  • SAML type: Required field is SamlMetadata
  • Other types (CUSTOM, EMAIL, etc.): All fields are optional

RequestParametersMap

Request parameter mapping for non-standard OAuth protocol parameter transformations. Can be empty by default. Configuration is needed when integrating with domestic platforms (e.g. WeChat, WeCom).

FieldRequiredTypeDescription
ClientIdNoStringMapped field name for OAuth standard client_id, e.g. appid for WeChat
ClientSecretNoStringMapped field name for OAuth standard client_secret
RedirectUriNoStringMapped field name for OAuth standard redirect_uri
GrantTypeNoStringParameter field name matching the OAuth authorization mode
ClientCredentialsNoStringOAuth authorization mode type, e.g. authorization_code, client_credentials
AccessTokenNoStringMapped field name for access_token in OAuth response
ExpiresInNoStringMapped field name for token validity period in OAuth response
AuthPositionNoStringRequest position for authentication info when obtaining token: URL, Headers, Body
RegisterUserRoleIdNoStringRole ID automatically bound when registering users through the identity source
RegisterUserAutoLicenseNoStringWhether to automatically grant a license when registering users, TRUE or FALSE, default FALSE
RegisterUserTypeNoStringUser type when registering: externalUser (external user) or internalUser (internal user), default externalUser

ResponseParametersMap

Response parameter mapping for non-standard OAuth protocol response parameter transformations. Can be empty by default. Configuration is needed when integrating with domestic platforms (e.g. WeChat, WeCom).

FieldRequiredTypeDescription
SubNoStringMapped field name for user unique identifier (sub), corresponding to OIDC standard sub
NameNoStringMapped field name for user name, corresponding to OIDC standard name
PictureNoStringMapped field name for user avatar, must be a publicly accessible URL
UsernameNoStringMapped field name for user login name, corresponding to OIDC standard preferred_username
EmailNoStringMapped field name for user email, corresponding to OIDC standard email
PhoneNumberNoStringMapped field name for user phone number, corresponding to OIDC standard phone_number
GroupsNoStringMapped field name for user roles/groups, corresponding to OIDC standard groups, supports string array

LocalizedMessage

Internationalized multi-language text structure, used for fields such as Name and Description of identity authentication sources. Different display texts can be configured for each language.

FieldRequiredTypeDescription
MessageYesStringDefault display text
LocalizedNoArray<MessageLocalized>Display text list for each language

MessageLocalized

FieldRequiredTypeDescription
MessageYesStringDisplay text for the language
LocaleYesStringLanguage identifier

Example:

{
Message: 'WeChat Login',
Localized: [
{ Message: 'WeChat Login', Locale: 'en' },
{ Message: '위챗 로그인', Locale: 'ko' }
]
}

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
const res = await app.env.getProviders()
console.log('Total authentication sources:', res.Total)
res.Data?.forEach(provider => {
console.log(`${provider.Id} (${provider.ProviderType}): ${provider.On}`)
})
}

test()

addProvider

1. API Description

API feature: Add an identity authentication source

API declaration: app.env.addProvider(params): Promise<Object>

version tip

This API has been supported since v5.1.0.

Creates a new identity authentication source under the specified TCB environment, supporting standard protocols such as OAuth 2.0, OIDC, SAML 2.0, as well as custom login and email login. An error will be returned if the identity source ID already exists. Each environment allows a maximum of 20 authentication sources.

2. Input Parameters

FieldRequiredTypeDescription
NameYesLocalizedMessageIdentity source display name, supports internationalized multi-language configuration
ProviderTypeYesStringIdentity source protocol type: OAUTH, OIDC, SAML, WX_MICRO_APP, WX_QRCODE_MICRO_APP, WX_CLOUDBASE_MICRO_APP, WX_MP, WX_OPEN, WX_WORK_INTERNAL, WX_WORK_AGENT, WX_WORK_THIRD_PARTY, WX_WORK_THIRD_PARTY_ASSOCIATION, CUSTOM, EMAIL
IdNoStringIdentity source unique identifier, 2-32 lowercase letters and digits. System auto-generates if not provided
PictureNoStringIdentity source icon URL, 64×64 SVG format recommended
HomepageNoStringIdentity source official homepage URL
ConfigNoObjectIdentity authentication source protocol connection configuration, see ProviderConfig
TransparentModeNoStringWhether to enable transparent mode, TRUE, FALSE, UNSPECIFIED, default FALSE
OnNoStringIdentity source enable status, TRUE, FALSE, UNSPECIFIED, default TRUE
DescriptionNoLocalizedMessageIdentity source description, supports internationalized multi-language configuration
ReuseUserIdNoStringWhether to reuse third-party user ID as platform user ID, TRUE, FALSE, UNSPECIFIED
AutoSignInWhenEmailMatchNoStringWhether to enable automatic email-based login association, default FALSE
AutoSignInWhenPhoneNumberMatchNoStringWhether to enable automatic phone number-based login association, default TRUE

3. Return Results

FieldTypeDescription
RequestIdStringUnique identifier of the request

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
// Add an OAuth identity authentication source
const res = await app.env.addProvider({
Name: { Message: 'My OAUTH Provider' },
ProviderType: 'OAUTH',
Id: 'myoauth',
Config: {
ClientId: 'your-client-id',
ClientSecret: 'your-client-secret',
AuthorizationEndpoint: 'https://www.example.com/auth',
TokenEndpoint: 'https://www.example.com/token',
UserinfoEndpoint: 'https://www.example.com/userinfo',
Scope: 'openid profile',
ResponseType: 'code',
TokenEndpointAuthMethod: 'CLIENT_SECRET_POST'
},
On: 'TRUE'
})
console.log(res.RequestId)
}

test()

modifyProvider

1. API Description

API feature: Modify an identity authentication source

API declaration: app.env.modifyProvider(params): Promise<Object>

version tip

This API has been supported since v5.1.0.

Updates the configuration of an existing identity authentication source, supporting modification of basic information, protocol connection configuration, login behavior control, and enable status. Uses an incremental update strategy, only updating fields that are passed in. Fields not included remain unchanged. For OIDC type, modifying the Issuer will automatically re-fetch endpoint configuration via Discovery. If a CUSTOM or EMAIL identity source does not exist, it will be automatically created upon invocation.

2. Input Parameters

FieldRequiredTypeDescription
IdYesStringIdentity source unique identifier, 2-32 lowercase letters and digits
NameNoLocalizedMessageIdentity source display name, supports internationalized multi-language configuration
PictureNoStringIdentity source icon URL
HomepageNoStringIdentity source official homepage URL
ProviderTypeNoStringIdentity source protocol type
ConfigNoObjectIdentity authentication source protocol connection configuration, see ProviderConfig
TransparentModeNoStringWhether to enable transparent mode. When enabled, ReuseUserId is forced to TRUE and AutoSignUpWithProviderUser is forced to FALSE
OnNoStringIdentity source enable status, TRUE, FALSE, UNSPECIFIED, default TRUE
DescriptionNoLocalizedMessageIdentity source description, supports internationalized multi-language configuration
ReuseUserIdNoStringWhether to reuse third-party user ID, TRUE, FALSE, UNSPECIFIED
AutoSignUpWithProviderUserNoStringWhether to automatically register system users, TRUE, FALSE, UNSPECIFIED
EmailConfigNoEmailConfigEmail identity source specific configuration, only valid when ProviderType is EMAIL
AutoSignInWhenEmailMatchNoStringWhether to enable automatic email-based login association, default FALSE
AutoSignInWhenPhoneNumberMatchNoStringWhether to enable automatic phone number-based login association, default TRUE

EmailConfig

Email identity source specific configuration for configuring email sending method and custom templates. Only valid when ProviderType is EMAIL. Referenced by modifyProvider.

FieldRequiredTypeDescription
OnNoStringWhether to use platform default sending, TRUE or FALSE
SmtpConfigNoSmtpConfigSMTP configuration
TemplateConfigNoEmailTemplateConfigEmail template configuration

SmtpConfig

Custom SMTP mail server connection configuration.

FieldRequiredTypeDescription
SenderAddressYesStringSender email address, displayed as the From header in the email
ServerHostYesStringSMTP server domain name or IP address, e.g. smtp.example.com
ServerPortYesNumberSMTP server port. Common values: 465 (SSL), 587 (STARTTLS), 25
AccountUsernameYesStringSMTP login account, typically the sender email address or SMTP username
AccountPasswordYesStringSMTP login password or authorization code. Keep it secure to prevent leakage
SecurityModeNoStringEncryption mode: AUTO (auto-select), SSL, STARTSSL, NO_SSL, default AUTO

EmailTemplateConfig

Email template configuration.

FieldRequiredTypeDescription
RegisterSignInNoLocalizedTemplateRegistration/sign-in template
DefaultTplNoLocalizedTemplateDefault template

Input restrictions: Templates must contain the {{.VerificationCode}} variable for displaying the verification code. Optional variables include {{.Usage}} (purpose description), {{.ExpireMinutes}} (expiration time), and {{.Email}} (recipient email). Templates must not contain script, javascript, onclick, onload, iframe, link tags, CSS expression, or CSS url().

LocalizedTemplate

Multi-language email template, specifying HTML template content by language code.

FieldRequiredTypeDescription
ZhCNNoStringChinese template, HTML format. Must contain the {{.VerificationCode}} variable. Optional variables: {{.Usage}}, {{.ExpireMinutes}}, {{.Email}}. Must not contain script, javascript, onclick, onload, iframe, link tags, CSS expression, or CSS url()
EnUSNoStringEnglish template, HTML format. Same variables and restrictions as ZhCN

Example:

{
RegisterSignIn: {
ZhCN: `
<h1>Verification Code</h1>
<p>Your verification code is: <strong>{{.VerificationCode}}</strong></p>
<p>Valid for 5 minutes</p>
`,
EnUS: `
<h1>Verification Code</h1>
<p>Your Verification Code Is: <strong>{{.VerificationCode}}</strong></p>
<p>expire in 5 min</p>
`
}
}

3. Return Results

FieldTypeDescription
RequestIdStringUnique identifier of the request

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
// Enable WeChat Open Platform login
const res = await app.env.modifyProvider({
Id: 'wx_open',
On: 'TRUE',
Config: {
ClientId: 'your-wechat-appid',
ClientSecret: 'your-wechat-appsecret'
}
})
console.log(res.RequestId)
}

test()

deleteProvider

1. API Description

API feature: Delete a third-party authentication source

API declaration: app.env.deleteProvider(id): Promise<Object>

version tip

This API has been supported since v5.1.0.

2. Input Parameters

FieldRequiredTypeDescription
IdYesStringAuthentication source ID, 2-32 lowercase letters or digits, e.g. github

3. Return Results

FieldTypeDescription
RequestIdStringUnique identifier of the request

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
const res = await app.env.deleteProvider('myoidc')
console.log(res.RequestId)
}

test()

createApiKey

1. API Description

API feature: Create an API Key

API declaration: app.env.createApiKey(params): Promise<Object>

version tip

This API has been supported since v5.1.0.

Creates an API Key access credential under the specified TCB environment. Two types are supported:

  • api_key: Server-side admin access credential with configurable validity period. Maximum 5 per environment
  • publish_key: Frontend anonymous access credential with fixed validity period. Only one per environment

Upon successful creation, the API Key plaintext token is returned. This value is only returned once at creation time. Please keep it secure.

2. Input Parameters

FieldRequiredTypeDescription
KeyTypeYesStringKey type: api_key or publish_key
KeyNameNoStringCustom key name. Descriptive names are recommended, e.g. server-prod
ExpireInNoNumberKey validity period in seconds, minimum 7200 seconds. 0 or not set means never expires

3. Return Results

FieldRequiredTypeDescription
RequestIdYesStringUnique identifier of the request
KeyIdYesStringAPI Key unique identifier
NameYesStringAPI Key name
ApiKeyNoStringAPI Key token value (JWT format), full plaintext only returned at creation
ExpireAtNoStringExpiration time, ISO 8601 format
CreateAtNoStringCreation time, ISO 8601 format

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
const res = await app.env.createApiKey({
KeyType: 'api_key',
KeyName: 'server-prod',
ExpireIn: 86400
})
console.log('KeyId:', res.KeyId)
console.log('ApiKey:', res.ApiKey) // Please keep it secure, only returned at creation
}

test()

describeApiKeyList

1. API Description

API feature: Query API Key list

API declaration: app.env.describeApiKeyList(params?): Promise<Object>

version tip

This API has been supported since v5.1.0.

Queries the list of API Key access credentials under the specified TCB environment with pagination, supporting type-based filtering. When type is not specified, only api_key type records are returned by default. Token values of api_key type are desensitized, while publish_key type returns full plaintext.

2. Input Parameters

FieldRequiredTypeDescription
KeyTypeNoStringKey type filter: api_key or publish_key, default api_key
PageNumberNoNumberPage number, starting from 1, default 1
PageSizeNoNumberNumber of items per page

3. Return Results

FieldRequiredTypeDescription
RequestIdYesStringUnique identifier of the request
DataNoArray<ApiKeyToken>API Key list
TotalNoNumberTotal count

ApiKeyToken

FieldRequiredTypeDescription
KeyIdNoStringAPI Key unique identifier
NameNoStringAPI Key name
ApiKeyNoStringAPI Key token value, desensitized for api_key type in list queries
ExpireAtNoStringExpiration time, ISO 8601 format
CreateAtNoStringCreation time, ISO 8601 format

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
const res = await app.env.describeApiKeyList({
KeyType: 'api_key',
PageNumber: 1,
PageSize: 10
})
console.log('Total:', res.Total)
res.Data?.forEach(key => {
console.log(`${key.Name} (${key.KeyId}): expires ${key.ExpireAt}`)
})
}

test()

deleteApiKey

1. API Description

API feature: Delete an API Key

API declaration: app.env.deleteApiKey(keyId): Promise<Object>

version tip

This API has been supported since v5.1.0.

Deletes a specific API Key server access credential under the specified TCB environment. After deletion, the token corresponding to the key will be revoked, and requests made using that key will fail. This operation is idempotent — if the specified API Key does not exist, success is returned directly.

2. Input Parameters

FieldRequiredTypeDescription
KeyIdYesStringKey unique identifier, obtainable via the key list query API

3. Return Results

FieldTypeDescription
RequestIdStringUnique identifier of the request

4. Sample Code

const CloudBase = require('@cloudbase/manager-node')
const app = new CloudBase({ secretId: 'Your SecretId', secretKey: 'Your SecretKey', envId: 'your-env-id' })

async function test() {
// First, query the API Key list
const listRes = await app.env.describeApiKeyList({ KeyType: 'api_key' })
if (listRes.Data?.length) {
const res = await app.env.deleteApiKey(listRes.Data[0].KeyId)
console.log(res.RequestId)
}
}

test()