tencent cloud

TencentDB for MySQL

DocumentationTencentDB for MySQL

Setting Account CAM Verification

Focus Mode
Font Size
Last updated: 2026-04-14 16:45:10
This document introduces the related instructions and operations for setting up account CAM authentication through the console.
Note:
If you need to enable account CAM authentication, please submit a ticket to apply for whitelisting.

Supported Region

This feature is currently available in the following regions: Shanghai, Guangzhou.

Background

In scenarios using cloud databases, it is usually necessary to create separate accounts and passwords for the database and authorize corresponding users for access and operations. This account management approach is relatively complex and prone to security issues such as account password leaks. Against this backdrop, TencentDB for MySQL supports enabling CAM authentication for accounts. By integrating Tencent Cloud platform sub-accounts with database accounts and adding CAM credential authentication, this feature simplifies account permission management complexity while enhancing database security and account management efficiency.

Scenarios

If users have high security requirements, they can use this feature to bind CAM with database account authentication. When making requests, users can obtain corresponding passwords to access the database, thereby enhancing database security. We recommend enabling CAM authentication in the following two scenarios.
Use CAM identity authentication as a mechanism for temporary personal access to the database.
Use CAM identity authentication only for workloads that can be retried easily.

Precautions

Please use persistent connections to access the database whenever possible.
Before CAM authentication is enabled, you need to configure the relevant CAM permission rules in advance.
After CAM authentication is enabled, password modification is not supported.
The root account also supports enabling CAM authentication.
After CAM authentication is disabled, you will not be able to obtain access credentials through CAM. Therefore, you need to enter a new password when CAM authentication is disabled.

Feature Limits

We recommend that no more than 10 accounts enable CAM authentication for a single instance.
After CAM authentication is enabled, resetting the password for this account is not supported.
The CAM authentication feature is only supported for accounts with a single host address.
The CAM authentication feature does not support repeated enabling for the same account name.
If an instance has enabled CAM authentication first, then it does not support enabling the password complexity feature.
If the instance has enabled the password complexity feature, adjusting password complexity rules is not supported after CAM authentication is enabled.

Prerequisites

You have submitted a ticket to apply to use this feature.
The instance status is Running.

Step 1: Configuring CAM Permission Rules

Before using the CAM authentication feature, you need to configure relevant CAM permission rules.

Policy Content

{
"statement": [
{
"action": [
"cam:BuildDataFlowAuthToken"
],
"effect": "allow",
"resource": [
"qcs::cam::uin/<User uin>:resourceUser/<Instance ID>/<Account name>",
]
}
],
"version": "2.0"
}
<User uin>: Replace it with the actual account ID.
<Instance ID>: Replace it with the actual ID of the instance that needs to be authorized.
<Account name>: Replace it with the actual name of the account that needs to be authorized.

Operation Guide

1. Log in to the CAM console using the admin account. On the Policies page, create a custom policy using the policy generator (see Creating Custom Policies via Policy Generator).

Effect: Allow.
Service: Access Management (cam).
Operation: Other Operations - BuildDataFlowAuthToken.
Resource: Specific Resource - Add Resource Six-segment.
Fill in the resource: <Instance ID>/<Account name>.
2. Click Next, customize the policy name, and grant the policy to the target sub-account.
3. Click Complete to complete authorization.

Step 2: Enabling CAM Authentication

Enabling CAM authentication involves two scenarios: enabling CAM authentication during account creation and enabling CAM authentication for an existing account. You can follow the steps below to perform operations respectively:
Scenario 1: Enable CAM Authentication When the Account is Created
Scenario 2: Enable CAM Authentication for Existing Accounts
1. Log in to the TencentDB for MySQL console.
2. In the instance list, click the Instance ID or the Manage option in the Operation column to go to the instance management page.
3. On the instance management page, choose Database Management > Account Management > Create Account, fill in the relevant information in the pop-up dialog box, and click OK after confirmation.
Note:
For the operation instructions on creating an account, see Create Account. The following describes only the steps related to enabling CAM authentication.
Enable CAM Verification: Toggle the button behind "Enable CAM Verification". After the important note in the pop-up window is read, click OK.
4. Accounts that have successfully Enabled CAM Verification will display "CAM Verification Enabled".
1. Log in to the TencentDB for MySQL console.
2. In the instance list, click the Instance ID or the Manage option in the Operation column to go to the instance management page.
3. On the instance management page, choose Database Management > Account Management.
4. On the account management page, find the target account, and in its Operation column, click Enable CAM Authentication.
5. After reading the important note in the pop-up window, click OK.
6. Accounts that have successfully Enabled CAM Verification will display "CAM Verification Enabled".

Step 3: Obtain the Password via Code in the Application

After the account has the relevant CAM permission rules and CAM authentication is enabled, users can obtain passwords through code calls such as Java in the application to connect to the database instance. You can also use Python to connect to the database instance; for specific methods, see Appendix 2: Connecting to the Database via Python. You can also use go to connect to the database instance; for specific methods, see Appendix 3: Connecting to the Database via go.
1. In the Tencent Cloud console, query the account AppID on the Account Information page.

2. Access CAM console > API Key Management and obtain SecretID and SecretKey.
3. Use the following code at the application side.
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-dbauth-sdk-java</artifactId>
<version>1.0.4</version>
</dependency>
Indirect dependency item: tencentcloud-sdk-java 3.1.1039 or later versions.
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.1.1039</version>
</dependency>
Example of obtaining a password through calling code
package com.tencentcloud.dbauth;
import com.tencentcloudapi.common.Credential;
import com.tencentcloud.dbauth.model.GenerateAuthenticationTokenRequest;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;

public class GenerateDBAuthentication {

public static void main(String[] args) {
// Define authentication token parameters.
String region = "<Instance region>";
String instanceId = "<Instance ID>";
String userName = "<Account name>";
// Obtain credentials from environment variables.
Credential credential = new Credential(System.getenv("<TENCENTCLOUD_SECRET_ID>"), System.getenv("<TENCENTCLOUD_SECRET_KEY>"));

System.out.println(getAuthToken(region, instanceId, userName, credential));
}

public static String getAuthToken(String region, String instanceId, String userName, Credential credential) {
try {
// Instantiate an http option (optional). Skip it if there are no special requirements.
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("cam.tencentcloudapi.com");
// Instantiate a client option (optional). Skip it if there are no special requirements.
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);

// Build GenerateAuthenticationTokenRequest.
GenerateAuthenticationTokenRequest tokenRequest = GenerateAuthenticationTokenRequest.builder()
.region(region)
.credential(credential)
.userName(userName)
.instanceId(instanceId)
.clientProfile(clientProfile) // clientProfile is optional.
.build();

return DBAuthentication.generateAuthenticationToken(tokenRequest);

} catch (TencentCloudSDKException e) {
e.printStackTrace();
}
return "";
}
}
<Instance region>: Replace it with the region of the instance that needs to be accessed. For example, ap-guangzhou.
<Instance ID>: Replace it with the actual ID of the instance that needs to be accessed.
<Account name>: Replace it with the actual login account name.
<TENCENTCLOUD_SECRET_ID>: Replace it with the SecretID obtained from the CAM console.
<TENCENTCLOUD_SECRET_KEY>: Replace it with the SecretKey obtained from the CAM console.

Step 4: Use an Authentication Token to Connect to TencentDB for MySQL

After obtaining the identity token AuthToken in Step 3, you can use the identity token to connect to TencentDB for MySQL, as shown in the following example.
mysql --host=<IP address> --port=<port number> --user=<account name> --password=<password>;
<IP address>: Replace it with the IP address of your instance.
<Port number>: Replace it with the port number of your instance. If the port number has not been modified, the default is 3306.
<Account name>: Replace it with the actual login account name.
<password>: replace with the AuthToken obtained in Step 3.

<Use java code to connect to the database sample>

package com.tencentcloud.examples;

import com.tencentcloud.dbauth.DBAuthentication;
import com.tencentcloud.dbauth.model.GenerateAuthenticationTokenRequest;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class CAMDatabaseAuthenticationTester {
public static void main(String[] args) throws Exception {
// Define the variables required for the connection.
String region = "ap-guangzhou";
String instanceId = "cdb-123456";
String userName = "test";
String host = "gz-cdb-123456.sql.tencentcdb.com";
int port = 3306;
String dbName = "mysql";
String secretId = System.getenv("TENCENTCLOUD_SECRET_ID");
String secretKey = System.getenv("TENCENTCLOUD_SECRET_KEY");

// Obtain a connection.
Connection connection = getDBConnectionUsingCAM(secretId, secretKey, region,
instanceId, userName, host, port, dbName);

// Verify whether the connection is successful.
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 'Success!';");
while (rs.next()) {
String id = rs.getString(1);
System.out.println(id); // Should print "Success!"
}

// Close the connection.
stmt.close();
connection.close();
}

/**
* Use CAM database authentication to obtain a database connection.
*
* @param secretId Secret ID
* @param secretKey Secret Key
* @param region Region
* @param instanceId Instance ID
* @param userName Username
* @param host Host
* @param port Port
* @param dbName Database Name
* @return Connection object
* @throws Exception exception
*/
private static Connection getDBConnectionUsingCAM(
String secretId, String secretKey, String region, String instanceId, String userName,
String host, int port, String dbName) throws Exception {

// Obtain credentials from secretId and secretKey
Credential credential = new Credential(secretId, secretKey);

// Define max retry attempts
int maxAttempts = 3;
Exception lastException = null;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
// Obtain an authentication token using credentials
String authToken = getAuthToken(region, instanceId, userName, credential);

String connectionUrl = String.format("jdbc:mysql://%s:%d/%s", host, port, dbName);
return DriverManager.getConnection(connectionUrl, userName, authToken);
} catch (Exception e) {
lastException = e;
System.out.println("Attempt " + attempt + " failed.");
Thread.sleep(5000);
}
}
System.out.println("All attempts failed. error: " + lastException.getMessage());
throw lastException;
}

/**
* Obtain an authentication token
*
* @param region Region
* @param instanceId Instance ID
* @param userName Username
* @param credential Credential
* @return Authentication token
*/
private static String getAuthToken(String region, String instanceId, String userName, Credential credential) throws TencentCloudSDKException {
// Instantiate an http option (optional). Skip it if there are no special requirements.
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("cam.tencentcloudapi.com");
// Instantiate a client option (optional). Skip it if there are no special requirements.
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);

// Build GenerateAuthenticationTokenRequest.
GenerateAuthenticationTokenRequest tokenRequest = GenerateAuthenticationTokenRequest.builder()
.region(region)
.credential(credential)
.userName(userName)
.instanceId(instanceId)
.clientProfile(clientProfile) // clientProfile is optional.
.build();

return DBAuthentication.generateAuthenticationToken(tokenRequest);
}
}

Modify password rotation cycle

After an account enables the CAM authentication feature, it supports modifying the password rotation period via the console.
Note:
After a new account is created for the instance and the password rotation period is set, the account's password rotation period will take effect immediately.
When an account with CAM authentication enabled exists under the instance, the password rotation period of this account will not take effect immediately after the password rotation period is modified. You need to refresh the password to make it take effect immediately. Otherwise, the account will be updated at the next password rotation cycle.
1. Log in to the TencentDB for MySQL console.
2. In the instance list, click the Instance ID or the Manage option in the Operation column to go to the instance management page.
3. On the instance management page, select Account Management.
4. Click Change password rotation cycle, then set the period in the pop-up window (The default value is 1 day. Valid range: 1 - 30 days. Only integers are supported.), and click OK.

Password refresh

After an account enables the CAM authentication feature, you can update the password by refreshing it. If the account has a rotation period set to change the password every 12 hours, you can immediately update the password by refreshing it before the rotation period is reached.
Note:
Note that after the password is refreshed, the current login credentials will become invalid. You need to observe whether the business access to the database meets expectations.
1. Log in to the TencentDB for MySQL console.
2. In the instance list, click the Instance ID or the Manage option in the Operation column to go to the instance management page.
3. On the instance management page, choose Database Management > Account Management.
4. In the account management page, locate the target account, and in its Operation column, click More > Refresh Password.
5. In the pop-up window, read the risk warning and click OK.

Disable CAM authentication

Note:
After CAM verification is disabled, you cannot obtain access credentials through CAM. Please update your password promptly.
1. Log in to the TencentDB for MySQL console.
2. In the instance list, click the Instance ID or the Manage option in the Operation column to go to the instance management page.
3. On the instance management page, choose Database Management > Account Management.
4. On the account management page, locate the target account, in its Operation column, click More > Disable CAM Verification.
5. In the pop-up window, enter the new password and confirm it, then click OK.

Appendix 1: Error Codes

If an Error field is present in the returned result, the API call has failed. For the description of error codes, see Error Codes.
Error codes related to the CAM authentication feature for TencentDB for MySQL accounts are as follows:

Public Error Codes

Error Code
Description
AuthFailure.InvalidAuthorization
The request header Authorization does not comply with the Tencent Cloud standard.
AuthFailure.InvalidSecretId
The secret key is invalid (not a TencentCloud API key type).
AuthFailure.MFAFailure
MFA error.
AuthFailure.SecretIdNotFound
The secret key does not exist. Please check in the console whether the key has been deleted or disabled. If the status is normal, please check whether the key is entered correctly, ensuring there are no spaces before or after.
AuthFailure.SignatureExpire
Signature expired. The difference between Timestamp and server time should not exceed five minutes. Please check whether the local time is synchronized with standard time.
AuthFailure.SignatureFailure
Signature error. Signature calculation error. Please refer to the signature method documentation in the API calling method and check the signature calculation process.
AuthFailure.TokenFailure
token error.
AuthFailure.UnauthorizedOperation
Request not authorized. See the CAM documentation for authentication details.

Business Error Codes

Error Code
Description
FailedOperation.BuildAuthToken
AuthToken generation exception.
FailedOperation.FlowAuthIllegal
Credentials operation failed.

Appendix 2: Using Python to Connect to a Database

1. In the Tencent Cloud console, query the account AppID on the Account Information page.

2. Access CAM console > API Key Management and obtain SecretID and SecretKey.
3. Install the TencentDB CAM Python SDK into your project via pip. Please run the following command in the command line:
pip install git+https://github.com/TencentCloud/dbauth-sdk-python.git
Note that if both python2 and python3 environments exist, the pip3 command should be used for installation in the python3 environment.
Indirect dependency item: tencentcloud-sdk-python version 3.0.1224 or later.

Using Python to Connect to a Database Example

import logging
import os
import time

import pymysql
from dbauth.db_authentication import DBAuthentication
from dbauth.model.generate_authentication_token_request import GenerateAuthenticationTokenRequest
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile

# Configure root logger
logging.basicConfig(
level=logging.INFO,
format='[%(asctime)s] - [%(threadName)s] - {%(module)s:%(funcName)s:%(lineno)d} %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
log = logging.getLogger(__name__)


def main():
region = "ap-guangzhou"
instance_id = "cdb-123456"
user_name = "camtest"
host = "gz-cdb-123456.sql.tencentcdb.com"
port = 25925
db_name = "test"
secret_id = os.environ['AK']
secret_key = os.environ['SK']

connection = None
try:
# Obtain the connection
connection = get_db_connection_using_cam(secret_id, secret_key, region,
instance_id, user_name, host, port, db_name)

# Verify whether the connection is successful.
with connection.cursor() as cursor:
cursor.execute("SELECT 'Success!';")
result = cursor.fetchone()
log.info(result[0]) # should print "Success!"
except Exception as e:
log.error(f"An error occurred: {e}")
finally:
if connection and connection.open:
connection.close()


def get_db_connection_using_cam(secret_id, secret_key, region, instance_id, user_name, host, port, db_name):
cred = credential.Credential(secret_id, secret_key)

max_attempts = 3
last_exception = None
for attempt in range(1, max_attempts + 1):
try:
auth_token = get_auth_token(region, instance_id, user_name, cred)

connection = pymysql.connect(
host=host,
port=port,
user=user_name,
password=auth_token,
database=db_name
)
return connection
except Exception as e:
last_exception = e
log.info(f"Attempt {attempt} failed.")
time.sleep(5)

log.error(f"All attempts failed. error: {last_exception}")
raise last_exception


def get_auth_token(region, instance_id, user_name, cred):
try:
# Instantiate an http option (optional). Skip it if there are no special requirements.
http_profile = HttpProfile()
http_profile.endpoint = "cam.tencentcloudapi.com"

# Instantiate a client option (optional). Skip it if there are no special requirements.
client_profile = ClientProfile()
client_profile.httpProfile = http_profile

request = GenerateAuthenticationTokenRequest(
region=region,
instance_id=instance_id,
user_name=user_name,
credential=cred,
client_profile=client_profile, # optional
)
return DBAuthentication.generate_authentication_token(request)
except TencentCloudSDKException as err:
log.error(err)
raise


if __name__ == "__main__":
main()


Appendix 3: Connect to a database using go

Dependency environment: go version 1.17 or later.
Indirect dependency item: tencentcloud-sdk-go version v1.0.1015 or later.
1. In the Tencent Cloud console, query the account AppID on the Account Information page.

2. Access CAM console > API Key Management and obtain SecretID and SecretKey.
3. Run the following command in the command line:
go get -v -u github.com/tencentcloud/dbauth-sdk-go

Sample for Using go to Connect to a Database

package main

import (
"database/sql"
"fmt"
"os"
"time"

_ "github.com/go-sql-driver/mysql"
"github.com/sirupsen/logrus"
"github.com/tencentcloud/dbauth-sdk-go/dbauth"
"github.com/tencentcloud/dbauth-sdk-go/dbauth/model"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
)

func init() {
logrus.SetOutput(os.Stdout)
logrus.SetFormatter(&logrus.TextFormatter{FullTimestamp: true})
logrus.SetLevel(logrus.InfoLevel)
}

func main() {
// Define database connection parameters
region := "ap-guangzhou"
instanceId := "cdb-123456"
userName := "camtest"
host := "gz-cdb-123456.sql.tencentcdb.com"
port := 3306
dbName := "test"
ak := os.Getenv("TENCENTCLOUD_SECRET_ID")
sk := os.Getenv("TENCENTCLOUD_SECRET_KEY")

// Obtain a connection.
connection, err := getDBConnectionUsingCam(ak, sk, region, instanceId, userName, host, port, dbName)
if err != nil {
logrus.Error("Failed to get connection:", err)
return
}

// Verify whether the connection is successful
stmt, err := connection.Query("SELECT 'Success!';")
if err != nil {
logrus.Error("Failed to execute query:", err)
return
}
for stmt.Next() {
var result string
stmt.Scan(&result)
logrus.Info(result) // Success!
}

// Close the connection.
if err := stmt.Close(); err != nil {
logrus.Error("Failed to close statement:", err)
}
if err := connection.Close(); err != nil {
logrus.Error("Failed to close connection:", err)
}
}

// Use CAM to obtain a database connection.
func getDBConnectionUsingCam(secretId, secretKey, region, instanceId, userName, host string, port int, dbName string) (*sql.DB, error) {
credential := common.NewCredential(secretId, secretKey)
maxAttempts := 3
var lastErr error

for attempt := 1; attempt <= maxAttempts; attempt++ {
// Obtain an authentication Token
authToken, err := getAuthToken(region, instanceId, userName, credential)
if err != nil {
return nil, err
}

connectionUrl := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", userName, authToken, host, port, dbName)
db, err := sql.Open("mysql", connectionUrl)
if err != nil {
lastErr = err
logrus.Warnf("Open connection failed. Attempt %d failed.", attempt)
time.Sleep(5 * time.Second)
continue
}
if err = db.Ping(); err != nil {
lastErr = err
logrus.Warnf("Ping failed. Attempt %d failed.", attempt)
time.Sleep(5 * time.Second)
continue
}
return db, nil
}

logrus.Error("All attempts failed. error:", lastErr)
return nil, lastErr
}

// Obtain an authentication Token
func getAuthToken(region, instanceId, userName string, credential *common.Credential) (string, error) {
// Instantiate a client option (optional). Skip it if there are no special requirements.
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = "cam.tencentcloudapi.com"
// Create a GenerateAuthenticationTokenRequest object. ClientProfile is optional.
tokenRequest, err := model.NewGenerateAuthenticationTokenRequest(region, instanceId, userName, credential, cpf)
if err != nil {
logrus.Errorf("Failed to create GenerateAuthenticationTokenRequest: %v", err)
return "", err
}

return dbauth.GenerateAuthenticationToken(tokenRequest)
}

Appendix 4: Connecting to the Database via PHP

ZTS PHP
NTS PHP

Dependencies

Dependencies: PHP 7.2 version and above.
PHP extension (Required):
ext-openssl (used for encryption and decryption).
ext-json (for JSON processing).
ext-parallel (for high-performance asynchronous timers, requires ZTS PHP).
ext-apcu (used for inter-process shared memory Token caching).
1. Before use, you need to Enable CAM Verification in the console.
2. In the Tencent Cloud console, query the account AppID on the Account Information page.
3. Access CAM console > API Key Managementand obtain SecretID and SecretKey.
Note:
Timer implementation:
Use the parallel extension to implement a high-performance asynchronous timer.
Modern PHP 8.x compatible threading solution.
Requires ZTS PHP + parallel extension.
Token caching:
Use APCu to implement inter-process shared memory caching (Required).
Automatically clean up expired tokens.

Use

Installing the SDK
composer require tencentcloud/dbauth-sdk-php
Install the PHP extension (Required).
parallel extension (Required - High-performance asynchronous timer): The parallel extension must be installed to support the auto-refresh feature.
# 1. Install ZTS PHP (Thread-Safe Version)
# Ubuntu/Debian:
sudo apt-get install php-zts php-dev

# CentOS/RHEL:
sudo yum install php-zts php-devel

# macOS (Using phpbrew):
phpbrew install <version> +default +zts
phpbrew switch <version>

# 2. Install the parallel extension
pecl install parallel

# 3. Enable the extension (Edit php.ini)
echo "extension=parallel.so" >> $(php -i | grep 'Loaded Configuration' | awk '{print $NF}')

# 4. Verify the installation
php -m | grep parallel
php -i | grep "Thread Safety" # should display "enabled"
APCu extension (Required - Shared Memory Token Cache): The APCu extension must be installed for inter-process shared memory Token caching.
# Install the APCu extension
pecl install apcu

# Enable in php.ini
echo "extension=apcu.so" >> /etc/php.ini
echo "apc.enable_cli=1" >> /etc/php.ini # Required for CLI usage

# Verify the installation
php -m | grep apcu

Important Notes

Timer Thread Management
Since the asynchronous timer feature of the parallel extension is used, timer threads must be manually cleaned up when the process ends:
// Call before the application exits to ensure all timer threads exit properly
\\TencentCloud\\DBAuth\\Internal\\TimerManager::cancelAllTimers();
Why is manual invocation required?
Threads created by the parallel extension do not automatically exit with the main process.
If not manually canceled, timer threads will continue to run, which can lead to resource leaks.

Sample of using PHP to connect to a database

<?php
require_once 'vendor/autoload.php';

use TencentCloud\\Common\\Credential;
use TencentCloud\\Common\\Profile\\ClientProfile;
use TencentCloud\\Common\\Profile\\HttpProfile;
use TencentCloud\\DBAuth\\DBAuthentication;
use TencentCloud\\DBAuth\\Model\\GenerateAuthenticationTokenRequest;

// Define database connection parameters.
$region = "ap-guangzhou";
$instanceId = "cdb-123456";
$userName = "camtest";
$host = "gz-cdb-123456.sql.tencentcdb.com";
$port = 3306;
$dbName = "test";
$ak = getenv("TENCENTCLOUD_SECRET_ID");
$sk = getenv("TENCENTCLOUD_SECRET_KEY");

// Obtain a connection.
$connection = getDBConnectionUsingCam($ak, $sk, $region, $instanceId, $userName, $host, $port, $dbName);

// Verify whether the connection has been established successfully.
$stmt = $connection->query("SELECT 'Success!';");
foreach ($stmt as $row) {
echo $row[0] . "\\n"; // Success!
}

// Close the connection.
$stmt = null;
$connection = null;

// Important: Manually cancel all timers at the end of the process to ensure threads exit properly.
\\TencentCloud\\DBAuth\\Internal\\TimerManager::cancelAllTimers();

// Use CAM to obtain a database connection.
function getDBConnectionUsingCam($secretId, $secretKey, $region, $instanceId, $userName, $host, $port, $dbName) {
$credential = new Credential($secretId, $secretKey);
$maxAttempts = 3;
$lastException = null;

for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
try {
// Obtain authentication Token
$authToken = getAuthToken($region, $instanceId, $userName, $credential);
$connectionUrl = "mysql:host=$host;port=$port;dbname=$dbName;charset=utf8mb4";
$pdo = new PDO($connectionUrl, $userName, $authToken, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// Test the connection.
$pdo->query("SELECT 1");
return $pdo;
} catch (Exception $e) {
$lastException = $e;
echo "Connection failed. Attempt $attempt failed.\\n";
sleep(5);
}
}

echo "All attempts failed. Error: " . $lastException->getMessage() . "\\n";
throw $lastException;
}

// Obtain authentication Token
function getAuthToken($region, $instanceId, $userName, $credential) {
// Instantiate a client option (optional). Skip it if there are no special requirements.
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint("cam.tencentcloudapi.com");
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
// Instantiate a GenerateAuthenticationTokenRequest object. ClientProfile is optional.
$request = GenerateAuthenticationTokenRequest::builder()
->region($region)
->instanceId($instanceId)
->userName($userName)
->credential($credential)
->clientProfile($clientProfile)
->build();

return DBAuthentication::generateAuthenticationToken($request);
}

Dependencies

Dependencies: PHP version 7.4 and above.
PHP extension (Required):
ext-openssl (used for encryption and decryption).
ext-json (for JSON processing).
ext-shmop (Required, for Token caching).
1. Before use, you need to Enable CAM Verification in the console.
2. In the Tencent Cloud console, query the account AppID on the Account Information page.
3. Access CAM console > API Key Managementand obtain SecretID and SecretKey.
Note:
Process Management:
All platforms (Windows/Linux/macOS): using proc_open() to implement the background timer process.
Clearing shared memory:
When the process is started, you need to call DBAuthentication::clearCache() to clear the shared memory and avoid accessing expired tokens.
Token caching (Required):
The shmop extension must be installed for Token caching.
To enable cross-process Token sharing (significantly improving performance and avoiding duplicate requests to CAM services).
Windows, Linux, and macOS are all supported.

Use

Installing the SDK
composer require tencentcloud/dbauth-sdk-php
Install the PHP extension (Required).
The shmop extension must be installed for Token caching:
Note:
The shmop extension is required. If it is not installed, the SDK will not function properly.
Linux(Ubuntu/Debian)
# shmop is usually built-in in PHP, verify whether it is enabled
php -m | grep shmop

# If not enabled, recompile PHP with the --enable-shmop option
# Or install a PHP package containing shmop
sudo apt-get update
sudo apt-get install php-common

# Restart PHP-FPM
sudo systemctl restart php-fpm
macOS
# shmop is usually built-in in PHP, verify whether it is enabled
php -m | grep shmop

# If not enabled, you may need to enable it in php.ini
# Or reinstall PHP via Homebrew
brew reinstall php

# If using PHP-FPM
brew services restart php
Windows
# shmop is usually built-in in PHP, verify whether it is enabled
php -m | grep shmop

# If not enabled, uncomment or add the following in php.ini:
extension=shmop

# Restart the Web server
Configuration (php.ini)
extension=shmop ; Enable the shmop extension

Important Notes

Please note the following important steps before using the SDK:
1. When the process starts: Call DBAuthentication::clearCache() to clear the shared memory and avoid accessing expired tokens.
2. When the process ends: Call TencentCloud\\DBAuth\\Internal\\TimerManager::cancelAllTimers() to properly clean up timer resources.

Sample of using PHP to connect to a database

<?php
require_once 'vendor/autoload.php';

use TencentCloud\\Common\\Credential;
use TencentCloud\\Common\\Profile\\ClientProfile;
use TencentCloud\\Common\\Profile\\HttpProfile;
use TencentCloud\\DBAuth\\DBAuthentication;
use TencentCloud\\DBAuth\\Model\\GenerateAuthenticationTokenRequest;
use TencentCloud\\DBAuth\\Internal\\Constants;
use TencentCloud\\DBAuth\\Internal\\TimerManager;

// Define database connection parameters.
$region = "ap-guangzhou";
$instanceId = "cdb-123456";
$userName = "camtest";
$host = "gz-cdb-123456.sql.tencentcdb.com";
$port = 3306;
$dbName = "test";
$ak = getenv("TENCENTCLOUD_SECRET_ID");
$sk = getenv("TENCENTCLOUD_SECRET_KEY");

// Clear the shared memory (Important: Call this when starting the process to avoid accessing expired tokens)
DBAuthentication::clearCache();

// Obtain a connection.
$connection = getDBConnectionUsingCam($ak, $sk, $region, $instanceId, $userName, $host, $port, $dbName);

// Verify whether the connection has been established successfully.
$stmt = $connection->query("SELECT 'Success!';");
foreach ($stmt as $row) {
echo $row[0] . "\\n"; // Success!
}

// Close the connection.
$stmt = null;
$connection = null;

// Cancel all timers (Important: Call this when the process ends to properly clean up timer resources)
TimerManager::cancelAllTimers();

// Use CAM to obtain a database connection.
function getDBConnectionUsingCam($secretId, $secretKey, $region, $instanceId, $userName, $host, $port, $dbName) {
$credential = new Credential($secretId, $secretKey);
$maxAttempts = 3;
$lastException = null;

for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
try {
// Obtain authentication Token
$authToken = getAuthToken($region, $instanceId, $userName, $credential);
$connectionUrl = "mysql:host=$host;port=$port;dbname=$dbName;charset=utf8mb4";
$pdo = new PDO($connectionUrl, $userName, $authToken, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// Test the connection.
$pdo->query("SELECT 'Success'");
return $pdo;
} catch (PDOException $e) {
$lastException = $e;
echo "Connection failed. Attempt $attempt failed.\\n";
sleep(5);
}
}

echo "All attempts failed. Error: " . $lastException->getMessage() . "\\n";
throw $lastException;
}

// Obtain an authentication Token
function getAuthToken($region, $instanceId, $userName, $credential) {
// Instantiate a client option (optional). Skip it if there are no special requirements.
$httpProfile = new HttpProfile();
$httpProfile->setEndpoint(Constants::CAM_ENDPOINT);
$clientProfile = new ClientProfile();
$clientProfile->setHttpProfile($httpProfile);
// Instantiate a GenerateAuthenticationTokenRequest object. ClientProfile is optional.
$request = GenerateAuthenticationTokenRequest::builder()
->region($region)
->instanceId($instanceId)
->userName($userName)
->credential($credential)
->clientProfile($clientProfile)
->build();

return DBAuthentication::generateAuthenticationToken($request);
}

Appendix 5: Connect to the Database via .NET

Dependencies

Requirements: .NET 6.0 and later versions.
1. Before use, you need to Enable CAM Verification in the console.
2. In the Tencent Cloud console, query the account AppID on the Account Information page.
3. Access CAM console > API Key Managementand obtain SecretID and SecretKey.

Indirect dependency

Requires TencentCloudSDK v3.0.1374 and later versions.
Note:
The version number is uniformly managed in the Directory.Build.props file. When updating dependencies, please modify the version property in this file to ensure version consistency across all projects.

Use

dotnet add package TencentCloudSDK --version 3.0.1374

Log configuration

To print the SDK logs, call DBAuthentication.SetLoggerFactory(loggerFactory) during initialization and pass in the ILoggerFactory instance:
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole().SetMinimumLevel(LogLevel.Information);
});

DBAuthentication.SetLoggerFactory(loggerFactory);

Using .NET to Connect to Database Sample

using System;
using System.Data;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using TencentCloud.Common;
using TencentCloud.Common.Profile;
using TencentCloud.DBAuth.SDK;
using TencentCloud.DBAuth.SDK.Internal;
using TencentCloud.DBAuth.SDK.Model;
using MySql.Data.MySqlClient;

// Note: This example requires the MySqlConnector package to establish a MySQL connection.
// To use this sample, add the following NuGet packages:
// dotnet add package MySqlConnector --version 2.3.7

namespace TencentCloud.DBAuth.SDK.Examples
{
public class ReadmeExample
{
public static async Task Main(string[] args)
{
// Configure logging
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole().SetMinimumLevel(LogLevel.Information);
});
DBAuthentication.SetLoggerFactory(loggerFactory);
var logger = loggerFactory.CreateLogger(typeof(ReadmeExample));

// Define authentication token parameters.
var region = "ap-guangzhou";
var instanceId = "cdb-123456";
var userName = "camtest";
var host = "gz-cdb-123456.sql.tencentcdb.com";
var port = 3306;
var dbName = "test";
var ak = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID");
var sk = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY");

if (string.IsNullOrEmpty(ak) || string.IsNullOrEmpty(sk))
{
logger.LogError("The TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY environment variables must be set.");
return;
}

// Obtain a database connection and automatically dispose of it after use.
using var connection = await GetDBConnectionUsingCam(ak, sk, region, instanceId, userName, host, port, dbName, logger);
if (connection == null)
{
logger.LogError("Failed to obtain connection");
return;
}

// Verify whether the connection is successful
// In a real application, you would use the connection here.
logger.LogInformation("Success! Database connection established.");
}

// Use CAM database authentication to obtain a database connection.
static async Task<IDbConnection> GetDBConnectionUsingCam(
string secretId, string secretKey, string region, string instanceId,
string userName, string host, int port, string dbName, ILogger logger)
{
var credential = new Credential
{
SecretId = secretId,
SecretKey = secretKey
};
const int maxAttempts = 3;
Exception? lastErr = null;

for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
try
{
// Obtain an authentication token using credentials
var authToken = GetAuthToken(region, instanceId, userName, credential);
if (string.IsNullOrEmpty(authToken))
{
throw new InvalidOperationException("Failed to obtain authentication token");
}

// Note: To use a MySQL connection, install the MySqlConnector package.
var connectionString = $"Server={host};Port={port};Database={dbName};User Id={userName};Password={authToken};";
var connection = new MySqlConnection(connectionString);
await connection.OpenAsync();
return connection;
}
catch (Exception ex)
{
lastErr = ex;
logger.LogWarning($"Failed to open connection. Attempt {attempt}/{maxAttempts} failed.");
if (attempt < maxAttempts)
{
logger.LogInformation("Waiting 5 seconds before retrying...");
await Task.Delay(5000);
}
}
}

logger.LogError($"All attempts failed. Error: {lastErr?.Message}");
return null;
}

// Obtain an authentication token
static string GetAuthToken(string region, string instanceId, string userName, Credential credential)
{
// Instantiate client configuration (optional). Skip it if there are no special requirements.
var clientProfile = new ClientProfile();
clientProfile.HttpProfile.Endpoint = Constants.CAM_EXTERNAL_ENDPOINT;
// Use the builder pattern to create a GenerateAuthenticationTokenRequest object
var tokenRequest = GenerateAuthenticationTokenRequest.NewBuilder()
.Region(region)
.InstanceId(instanceId)
.UserName(userName)
.Credential(credential)
.ClientProfile(clientProfile)
.Build();

return DBAuthentication.GenerateAuthenticationToken(tokenRequest);
}
}
}

Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback