{"statement": [{"action": ["cam:BuildDataFlowAuthToken"],"effect": "allow","resource": ["qcs::cam::uin/<User uin>:resourceUser/<Instance ID>/<Username>",]}],"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 = "<Username>";// 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 "";}}
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=<Database name>;user=<Username>;password=<Password>;encrypt=false;";Connection con = DriverManager.getConnection(connectionUrl);
Error Code | Description |
AuthFailure.InvalidAuthorization | The Authorization in the request header does not comply with Tencent Cloud standards. |
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. Check in the console whether the key has been deleted or disabled. If the status is normal, check whether the key is entered correctly, and ensure there are no spaces before or after it. |
AuthFailure.SignatureExpire | The signature has expired. The difference between the Timestamp and the server time must not exceed five minutes. Please check whether the local time is synchronized with the standard time. |
AuthFailure.SignatureFailure | Signature error. The signature calculation is incorrect. Please check the signature calculation process against the signature method documentation in the calling method. |
AuthFailure.TokenFailure | token error. |
AuthFailure.UnauthorizedOperation |
Error Code | Description |
FailedOperation.BuildAuthToken | AuthToken generation exception. |
FailedOperation.FlowAuthIllegal | Credential operation failed. |

pip install git+https://github.com/TencentCloud/dbauth-sdk-python.git
import loggingimport osimport timeimport pymssqlfrom 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 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 = "mssql-123456"user_name = "camtest"host = "gz-mssql-123456.sql.tencentcdb.com"port = 24398db_name = "test"secret_id = os.environ['AK']secret_key = os.environ['SK']connection = Nonetry:# Obtain a 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]) # This should print "Success!"except Exception as e:log.error(f"An error occurred: {e}")finally:if connection: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 = pymssql.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()
proc_open() to implement the background timer process.DBAuthentication::clearCache() to clear the shared memory, preventing access to expired tokens.composer require tencentcloud/dbauth-sdk-php
# shmop is usually built into PHP. Verify whether it is enabled.php -m | grep shmop# If it is not enabled, you need to recompile PHP with the --enable-shmop option.# Or install a PHP package that includes shmop.sudo apt-get updatesudo apt-get install php-common# Restart PHP-FPMsudo systemctl restart php-fpm
# shmop is usually built into PHP. Verify whether it is enabled.php -m | grep shmop# If it is not enabled, you may need to enable it in php.ini.# Or reinstall PHP via Homebrew.brew reinstall php# If you use PHP-FPMbrew services restart php
# shmop is usually built into PHP. Verify whether it is enabled.php -m | grep shmop# If it is not enabled, uncomment or add the following line in php.ini:extension=shmop# Restart the Web server.
extension=shmop ; Enable the shmop extension
<?php/*** Copyright (c) 2024 Tencent Cloud** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/// Disable deprecation warnings (PHP 8.5 compatibility)// TencentCloud SDK's AbstractModel uses deprecated ReflectionProperty::setAccessible()// This does not affect functionality but will produce warning messageserror_reporting(E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED);require_once __DIR__ . '/../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\\Logger;// Configure loggingdate_default_timezone_set('Asia/Shanghai');// Set DBAuth log level to ERROR (only show errors, hide INFO logs)Logger::setLogLevel(Logger::ERROR);function logger($level, $message) {$timestamp = date('Y-m-d H:i:s');echo "[{$timestamp}] [{$level}] {$message}\\n";}/*** Get database connection (using CAM authentication)*/function getDBConnectionUsingCAM($secretId, $secretKey, $region, $instanceId, $userName, $host, $port, $dbName) {$credential = new Credential($secretId, $secretKey);$maxAttempts = 3;$lastError = null;for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {try {// Get authentication token$authToken = getAuthToken($region, $instanceId, $userName, $credential);// Connect to SQL Server using dblib driver, specify database in DSN$dsn = "dblib:host={$host}:{$port};dbname={$dbName};charset=UTF-8";$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_TIMEOUT => 10,];// Create PDO connection, connect directly to specified database$pdo = new PDO($dsn, $userName, $authToken, $options);// Test connection$pdo->query("SELECT 'Success!'");return $pdo;} catch (Exception $e) {$lastError = $e;logger('WARN', "Connection attempt {$attempt} failed: " . $e->getMessage());if ($attempt < $maxAttempts) {logger('INFO', 'Retrying in 5 seconds...');sleep(5);}}}logger('ERROR', "All {$maxAttempts} attempts failed");throw new Exception('Failed to connect to database: ' . $lastError->getMessage());}/*** Get authentication token*/function getAuthToken($region, $instanceId, $userName, $credential) {// Configure HTTP Profile$httpProfile = new HttpProfile();$httpProfile->setEndpoint('cam.tencentcloudapi.com');$httpProfile->setReqTimeout(5);$clientProfile = new ClientProfile();$clientProfile->setHttpProfile($httpProfile);// Create request object$request = GenerateAuthenticationTokenRequest::builder()->region($region)->instanceId($instanceId)->userName($userName)->credential($credential)->clientProfile($clientProfile)->build();// Generate authentication tokenreturn DBAuthentication::generateAuthenticationToken($request);}try {// Get credentials from environment variables$secretId = getenv('TENCENTCLOUD_SECRET_ID');$secretKey = getenv('TENCENTCLOUD_SECRET_KEY');if (empty($secretId) || empty($secretKey)) {throw new Exception('Please set TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY environment variables');}// Database configuration$region = 'ap-guangzhou';$instanceId = 'mssql-test123';$userName = 'test_db_1';$host = 'gz-mssql-test123.sql.tencentcdb.com';$port = 3306;$dbName = 'testdb';// Clean up shared memoryDBAuthentication::clearCache();logger('INFO', '==========================================');logger('INFO', 'SQL Server Connection Example (CAM Auth)');logger('INFO', '==========================================');logger('INFO', "Region: {$region}");logger('INFO', "Instance ID: {$instanceId}");logger('INFO', "Host: {$host}:{$port}");logger('INFO', "Database: {$dbName}");logger('INFO', "User: {$userName}");logger('INFO', '==========================================');// Loop connection test (simulating actual usage scenario)for ($i = 1; $i <= 100; $i++) {logger('INFO', "Iteration {$i}/100");// Get database connection$connection = getDBConnectionUsingCAM($secretId,$secretKey,$region,$instanceId,$userName,$host,$port,$dbName);// Execute query$stmt = $connection->query("SELECT 'Success!'");$result = $stmt->fetch();logger('INFO', "Query result: " . json_encode($result));// Close connection$connection = null;// Wait 1 secondsleep(1);}logger('INFO', '==========================================');logger('INFO', 'All iterations completed successfully!');logger('INFO', '==========================================');} catch (Exception $e) {logger('ERROR', 'Failed to connect to SQL Server: ' . $e->getMessage());logger('ERROR', 'Stack trace: ' . $e->getTraceAsString());}
dotnet add package TencentCloudSDK --version 3.0.1374
DBAuthentication.SetLoggerFactory(loggerFactory) during initialization and pass in an ILoggerFactory instance:using var loggerFactory = LoggerFactory.Create(builder =>{builder.AddConsole().SetMinimumLevel(LogLevel.Information);});DBAuthentication.SetLoggerFactory(loggerFactory);
using System;using Microsoft.Data.SqlClient;using Microsoft.Extensions.Logging;using TencentCloud.Common;using TencentCloud.DBAuth.SDK;using TencentCloud.DBAuth.SDK.Model;namespace SqlServerExample{/// <summary>/// SQL Server example using CAM authentication/// </summary>public static class SqlServerExample{private static ILogger? _logger;/// <summary>/// Main entry point for SQL Server example/// </summary>/// <param name="args">Command line arguments</param>public static void Main(string[] args){_logger = LoggerFactory.Create(builder => builder.AddConsole()).CreateLogger(typeof(SqlServerExample));try{// SQL Server hardcoded parametersconst string region = "ap-guangzhou";const string instanceId = "mssql-test123";const string user = "test_sqlserver";const string host = "gz-mssql-test123.sql.tencentcdb.com";const int port = 3306;const string database = "test0";const int times = 100;const int interval = 1000; // milliseconds_logger.LogInformation($"Sqlserver Example - Region: {region}, InstanceId: {instanceId}");_logger.LogInformation($"Host: {host}:{port}, Database: {database}, User: {user}");// Get credentials from environment variables and connect to databaseTestSqlServerConnection(region, instanceId, user, host, port, database, times, interval);_logger.LogInformation("SqlServer example completed successfully");}catch (Exception ex){_logger.LogError(ex, "SqlServer example failed, error: {ex.Message}", ex.Message);Environment.Exit(1);}}/// <summary>/// Get auth token from environment variables/// </summary>private static string GetAuthTokenFromEnv(string region, string instanceId, string user){var secretId = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID");var secretKey = Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY");if (string.IsNullOrEmpty(secretId) || string.IsNullOrEmpty(secretKey)){throw new InvalidOperationException("Environment variables TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY must be set");}var credential = new Credential{SecretId = secretId,SecretKey = secretKey};return GetAuthToken(region, instanceId, user, credential);}/// <summary>/// Get database authentication token/// </summary>private static string GetAuthToken(string region, string instanceId, string userName, Credential credential){try{var tokenRequest = GenerateAuthenticationTokenRequest.NewBuilder().Region(region).Credential(credential).UserName(userName).InstanceId(instanceId).Build();var authToken = DBAuthentication.GenerateAuthenticationToken(tokenRequest);_logger.LogInformation($"Generated auth token for instance {instanceId}, user {userName}");return authToken;}catch (Exception ex){_logger.LogError(ex, "Failed to generate auth token, error: {ex.Message}", ex.Message);return string.Empty;}}/// <summary>/// Test SQL Server connection/// </summary>private static void TestSqlServerConnection(string region, string instanceId, string user,string host, int port, string database, int times, int interval){const int maxAttempts = 3;for (int i = 0; i < times; i++){Exception? lastError = null;bool success = false;// Retry mechanismfor (int attempt = 1; attempt <= maxAttempts; attempt++){try{var authToken = GetAuthTokenFromEnv(region, instanceId, user);var result = TestConnectionSqlServer(host,port,user,database,authToken);if (result == null){_logger.LogWarning($"Iteration {i} returned null result");}else{_logger.LogInformation($"Iteration {i} succeeded, result: {result}");success = true;break;}}catch (Exception ex){lastError = ex;if (attempt < maxAttempts){System.Threading.Thread.Sleep(5000);}}}if (!success){throw new Exception($"Failed to connect to database: {lastError?.Message}");}if (i < times - 1){System.Threading.Thread.Sleep(interval);}}}/// <summary>/// Test SQL Server database connection/// </summary>private static string TestConnectionSqlServer(string ip, int port, string user, string dbName, string authToken){string output = "";try{var connectionString = $"Server={ip},{port};Database={dbName};User Id={user};Password={authToken};TrustServerCertificate=true;Connection Timeout=30;";using var connection = new SqlConnection(connectionString);connection.Open();const string sql = "SELECT 'Success'";using var command = connection.CreateCommand();command.CommandText = sql;using var reader = command.ExecuteReader();if (reader.Read()){var result = reader.GetString(0);output = $"Connection: {sql} Result: {result}";}}catch (Exception ex){_logger.LogError(ex, "SqlServer connection failed,error: {ex.Message}", ex.Message);throw;}return output;}}}
Esta página foi útil?
Você também pode entrar em contato com a Equipe de vendas ou Enviar um tíquete em caso de ajuda.
comentários