{"statement": [{"action": ["cam:BuildDataFlowAuthToken"],"effect": "allow","resource": ["qcs::cam::uin/<User uin>:resourceUser/<Instance ID>/<Account name>",]}],"version": "2.0"}


<dependency><groupId>com.tencentcloudapi</groupId><artifactId>tencentcloud-dbauth-sdk-java</artifactId><version>1.0.4</version></dependency>
<dependency><groupId>com.tencentcloudapi</groupId><artifactId>tencentcloud-sdk-java</artifactId><version>3.1.1039</version></dependency>
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 "";}}
mysql --host=<IP address> --port=<port number> --user=<account name> --password=<password>;
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 secretKeyCredential credential = new Credential(secretId, secretKey);// Define max retry attemptsint maxAttempts = 3;Exception lastException = null;for (int attempt = 1; attempt <= maxAttempts; attempt++) {try {// Obtain an authentication token using credentialsString 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);}}
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 |
Error Code | Description |
FailedOperation.BuildAuthToken | AuthToken generation exception. |
FailedOperation.FlowAuthIllegal | Credentials operation failed. |

pip install git+https://github.com/TencentCloud/dbauth-sdk-python.git
import loggingimport osimport timeimport pymysqlfrom dbauth.db_authentication import DBAuthenticationfrom dbauth.model.generate_authentication_token_request import GenerateAuthenticationTokenRequestfrom tencentcloud.common import credentialfrom tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKExceptionfrom tencentcloud.common.profile.client_profile import ClientProfilefrom tencentcloud.common.profile.http_profile import HttpProfile# Configure root loggerlogging.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 = 25925db_name = "test"secret_id = os.environ['AK']secret_key = os.environ['SK']connection = Nonetry:# Obtain the connectionconnection = 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 = 3last_exception = Nonefor 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 connectionexcept Exception as e:last_exception = elog.info(f"Attempt {attempt} failed.")time.sleep(5)log.error(f"All attempts failed. error: {last_exception}")raise last_exceptiondef 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_profilerequest = 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)raiseif __name__ == "__main__":main()

go get -v -u github.com/tencentcloud/dbauth-sdk-go
package mainimport ("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 parametersregion := "ap-guangzhou"instanceId := "cdb-123456"userName := "camtest"host := "gz-cdb-123456.sql.tencentcdb.com"port := 3306dbName := "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 successfulstmt, err := connection.Query("SELECT 'Success!';")if err != nil {logrus.Error("Failed to execute query:", err)return}for stmt.Next() {var result stringstmt.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 := 3var lastErr errorfor attempt := 1; attempt <= maxAttempts; attempt++ {// Obtain an authentication TokenauthToken, 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 = errlogrus.Warnf("Open connection failed. Attempt %d failed.", attempt)time.Sleep(5 * time.Second)continue}if err = db.Ping(); err != nil {lastErr = errlogrus.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 Tokenfunc 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)}
composer require tencentcloud/dbauth-sdk-php
# 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 +ztsphpbrew switch <version># 2. Install the parallel extensionpecl install parallel# 3. Enable the extension (Edit php.ini)echo "extension=parallel.so" >> $(php -i | grep 'Loaded Configuration' | awk '{print $NF}')# 4. Verify the installationphp -m | grep parallelphp -i | grep "Thread Safety" # should display "enabled"
# Install the APCu extensionpecl install apcu# Enable in php.iniecho "extension=apcu.so" >> /etc/php.iniecho "apc.enable_cli=1" >> /etc/php.ini # Required for CLI usage# Verify the installationphp -m | grep apcu
// Call before the application exits to ensure all timer threads exit properly\\TencentCloud\\DBAuth\\Internal\\TimerManager::cancelAllTimers();
<?phprequire_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 Tokenfunction 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);}
proc_open() to implement the background timer process.DBAuthentication::clearCache() to clear the shared memory and avoid accessing expired tokens.composer require tencentcloud/dbauth-sdk-php
# shmop is usually built-in in PHP, verify whether it is enabledphp -m | grep shmop# If not enabled, recompile PHP with the --enable-shmop option# Or install a PHP package containing shmopsudo apt-get updatesudo apt-get install php-common# Restart PHP-FPMsudo systemctl restart php-fpm
# shmop is usually built-in in PHP, verify whether it is enabledphp -m | grep shmop# If not enabled, you may need to enable it in php.ini# Or reinstall PHP via Homebrewbrew reinstall php# If using PHP-FPMbrew services restart php
# shmop is usually built-in in PHP, verify whether it is enabledphp -m | grep shmop# If not enabled, uncomment or add the following in php.ini:extension=shmop# Restart the Web server
extension=shmop ; Enable the shmop extension
<?phprequire_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 Tokenfunction 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);}
dotnet add package TencentCloudSDK --version 3.0.1374
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 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.7namespace TencentCloud.DBAuth.SDK.Examples{public class ReadmeExample{public static async Task Main(string[] args){// Configure loggingusing 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 credentialsvar 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 tokenstatic 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 objectvar tokenRequest = GenerateAuthenticationTokenRequest.NewBuilder().Region(region).InstanceId(instanceId).UserName(userName).Credential(credential).ClientProfile(clientProfile).Build();return DBAuthentication.GenerateAuthenticationToken(tokenRequest);}}}
Was this page helpful?
You can also Contact sales or Submit a Ticket for help.
Help us improve! Rate your documentation experience in 5 mins.
Feedback