设置账号 CAM 验证

最近更新时间:2026-04-28 10:52:02

我的收藏
本文为您介绍通过控制台设置账号 CAM 验证相关说明和操作。
说明:
如果您需要开启账号 CAM 验证,请您填写 申请单 申请使用。

支持地域

此功能目前支持的地域为:上海、广州。

背景

在使用云数据库的场景中,通常需要为数据库创建独立的账号和密码,并授权给相应的用户进行访问和操作。这种方式的账户管理比较复杂,容易出现账号密码泄露等安全问题。基于以上背景,云数据库 SQL Server 支持为账号启用 CAM 验证功能,通过打通腾讯云平台子账号与数据库账号之间的关系以及增加 CAM 凭证的身份验证,简化账号权限管理的复杂度,提升数据库的安全性和账号管理效率。

操作场景

如果用户对安全性有较高要求,可以通过本功能将 CAM 与数据库账号验证相绑定,用户在请求时可获取对应的密码来访问数据库,以提升数据库的安全性。我们建议如下两种场景,启用 CAM 验证。
使用 CAM 身份验证作为临时、个人访问数据库的机制时。
仅对可以轻松重试的工作负载使用 CAM 身份验证。

注意事项

请尽可能使用长连接访问数据库。
启用 CAM 验证前需要提前配置好相关 CAM 权限规则。
启用 CAM 验证后不支持修改密码。
关闭 CAM 验证后将无法通过 CAM 获取访问凭证,因此在关闭 CAM 验证时需要输入一个新密码。

功能限制

单个实例内建议不超过10个账号开启 CAM 验证。
启用 CAM 验证后不支持对该账号进行重置密码操作。
仅支持单个主机地址的账户启用 CAM 验证功能。
相同账号名不支持重复启用 CAM 验证功能。
root 账号不支持启用 CAM 验证功能。

前提条件

已填写 申请单 申请使用此功能。
实例状态为运行中。

步骤1:配置 CAM 权限规则

在使用账号 CAM 验证功能之前,用户需要先配置相关的 CAM 权限规则。

策略内容

{
"statement": [
{
"action": [
"cam:BuildDataFlowAuthToken"
],
"effect": "allow",
"resource": [
"qcs::cam::uin/<用户 uin>:resourceUser/<实例 ID>/<账号名>",
]
}
],
"version": "2.0"
}
<用户 uin>:替换为实际的账号 ID。
<实例 ID>:替换为实际需要授权的实例 ID。
<账号名>:替换为实际需要授权的账号名。

操作指引

1. 使用管理员账号登录访问管理控制台,在 策略 页面,按照策略生成器创建自定义策略(请参见 通过策略生成器创建自定义策略)。

效果:允许
服务:访问管理(cam)
操作:其他操作 - BuildDataFlowAuthToken
资源:特定资源 - 添加资源六段式
填写资源:<实例 ID>/<账号名>
2. 单击下一步,自定义策略的名称,并将策略授予目标子账号。
3. 单击完成,完成授权。

步骤2:启用 CAM 验证

启用 CAM 验证分为两种情形,分别是创建账号时启用 CAM 验证和为已有账号启用 CAM 验证,您可按照如下步骤分别操作。
情形1:创建账号时启用 CAM 验证
情形2:为已有账号启用 CAM 验证
2. 在实例列表,单击实例 ID操作列的管理,进入实例管理页面。
3. 在实例管理页面,选择账号管理 > 创建账号,在弹出的对话框填写相关信息,确认无误后单击确定。
说明:
创建不同权限账号的操作介绍请参考 账号管理,以下仅介绍开启 CAM 验证相关的步骤。
启用 CAM 验证:打开“启用 CAM 验证”后的按钮,在弹窗下阅读重要提示后单击确定

4. 成功启用 CAM 验证的账号显示如下图。

2. 在实例列表,单击实例 ID操作列的管理,进入实例管理页面。
3. 在实例管理页面,选择账号管理
4. 在账号管理页面,找到目标账号,在其操作列单击启用 CAM 验证
5. 在弹窗下阅读重要提示后,单击确定

6. 成功启用 CAM 验证的账号显示如下图。


步骤3:在应用程序通过代码调用获取密码

账号具备了相关 CAM 权限规则,并且启用了 CAM 验证后,用户可在应用程序通过 Java 等代码调用来获取密码,从而连接数据库实例。
1. 在腾讯云控制台,账号信息 页面,查询账号的 APPID。

2. 访问管理控制台 > API 密钥管理 获取 SecretID 和 SecretKey。
3. 在应用程序使用如下代码。
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-dbauth-sdk-java</artifactId>
<version>1.0.4</version>
</dependency>
间接依赖项:tencentcloud-sdk-java 3.1.1039版本及以上。
<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) {
// 定义认证令牌的参数
String region = "<实例所在地域>";
String instanceId = "<实例 ID>";
String userName = "<账号名>";
// 从环境变量中获取凭证
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 {
// 实例化一个 http 选项,可选的,没有特殊需求可以跳过
HttpProfile httpProfile = new HttpProfile();
httpProfile.setEndpoint("cam.tencentcloudapi.com");
// 实例化一个 client 选项,可选的,没有特殊需求可以跳过
ClientProfile clientProfile = new ClientProfile();
clientProfile.setHttpProfile(httpProfile);

// 构建 GenerateAuthenticationTokenRequest
GenerateAuthenticationTokenRequest tokenRequest = GenerateAuthenticationTokenRequest.builder()
.region(region)
.credential(credential)
.userName(userName)
.instanceId(instanceId)
.clientProfile(clientProfile) // clientProfile 是可选的
.build();

return DBAuthentication.generateAuthenticationToken(tokenRequest);

} catch (TencentCloudSDKException e) {
e.printStackTrace();
}
return "";
}
}
<实例所在地域>:替换为您需要访问的实例所在地域,示例:ap-guangzhou。
<实例 ID>:替换为需要访问的实例 ID。
<账号名>:替换为实际登录的账号名。
<TENCENTCLOUD_SECRET_ID>:替换为从访问管理控制台获取到的 SecretID。
<TENCENTCLOUD_SECRET_KEY>:替换为从访问管理控制台获取到的 SecretKey。

步骤4:使用身份令牌连接云数据库 SQL Server

说明:
使用 JDBC 驱动程序连接是 Java 程序连接到关系型数据库的标准方式,详细 JDBC 驱动程序的安装以及连接方法,可参见 Using the JDBC driver
步骤3 中获取到身份令牌 AuthToken 后,即可使用身份令牌连接云数据库 SQL Server,以下连接命令为使用 JDBC 连接数据库的场景示例。
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=<数据库名>;user=<账号名>;password=<密码>;encrypt=false;";
Connection con = DriverManager.getConnection(connectionUrl);
<数据库名>:替换为您实际需要访问的数据库名称。
<账号名>:替换为您实际登录的账号名。
<密码>:替换为 步骤3 中获取到的 AuthToken。

刷新密码

当账号启用 CAM 验证功能后,可以通过刷新密码操作来更新密码。如果该账号设置的轮转周期为12小时更换一次密码,则在未到达轮转周期之前,可以通过刷新密码操作来立即更新密码。
注意:
注意刷新密码后,当前登录凭证会失效,需要观察业务访问数据库状态是否符合预期。
2. 在实例列表,单击实例 ID操作列的管理,进入实例管理页面。
3. 在实例管理页面,选择账号管理。
4. 在账号管理页面,找到目标账号,在其操作列单击刷新密码
5. 在弹窗下阅读风险提示后,单击确定


关闭 CAM 验证

注意:
关闭 CAM 验证后无法通过 CAM 获取访问凭证,请及时更新密码。
2. 在实例列表,单击实例 ID操作列的管理,进入实例管理页面。
3. 在实例管理页面,选择账号管理。
4. 在账号管理页面,找到目标账号,在其操作列单击关闭 CAM 验证
5. 在弹窗下输入新密码并确认密码后单击确定


附录1:错误码

如果返回结果中存在 Error 字段,则表示调用 API 接口失败。有关错误码的说明,请参见 错误码
云数据库 SQL Server 账号 CAM 验证功能相关的错误码如下:

公共错误码

错误码
说明
AuthFailure.InvalidAuthorization
请求头部的 Authorization 不符合腾讯云标准。
AuthFailure.InvalidSecretId
密钥非法(不是云 API 密钥类型)。
AuthFailure.MFAFailure
MFA 错误。
AuthFailure.SecretIdNotFound
密钥不存在。请在 控制台 检查密钥是否已被删除或者禁用,如状态正常,请检查密钥是否填写正确,注意前后不得有空格。
AuthFailure.SignatureExpire
签名过期。Timestamp 和服务器时间相差不得超过五分钟,请检查本地时间是否和标准时间同步。
AuthFailure.SignatureFailure
签名错误。签名计算错误,请对照调用方式中的签名方法文档检查签名计算过程。
AuthFailure.TokenFailure
token 错误。
AuthFailure.UnauthorizedOperation
请求未授权。请参考 CAM 文档对鉴权的说明。

业务错误码

错误码
说明
FailedOperation.BuildAuthToken
生成 AuthToken 异常。
FailedOperation.FlowAuthIllegal
凭据操作失败。

附录2:通过 Python 连接数据库

1. 在腾讯云控制台,账号信息 页面,查询账号的 APPID。

2. 访问管理控制台 > API 密钥管理 获取 SecretID 和 SecretKey。
3. 通过 pip 安装方式将腾讯云数据库 CAM Python SDK 安装到您的项目中。请在命令行中执行以下命令:
pip install git+https://github.com/TencentCloud/dbauth-sdk-python.git
请注意,如果同时有 python2 和 python3 环境,python3 环境需要使用 pip3 命令安装。
间接依赖项:tencentcloud-sdk-python 3.0.1224版本及以上。

使用 Python 连接数据库示例

import logging
import os
import time

import pymssql
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

# 配置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 = 24398
db_name = "test"
secret_id = os.environ['AK']
secret_key = os.environ['SK']

connection = None
try:
# 获取连接
connection = get_db_connection_using_cam(secret_id, secret_key, region,
instance_id, user_name, host, port, db_name)

# 验证连接是否成功
with connection.cursor() as cursor:
cursor.execute("SELECT 'Success!';")
result = cursor.fetchone()
log.info(result[0]) # 应该打印 "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 = 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 = pymssql.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:
# 实例化一个 http 选项,可选的,没有特殊需求可以跳过
http_profile = HttpProfile()
http_profile.endpoint = "cam.tencentcloudapi.com"

# 实例化一个 client 选项,可选的,没有特殊需求可以跳过
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, # 可选
)
return DBAuthentication.generate_authentication_token(request)
except TencentCloudSDKException as err:
log.error(err)
raise


if __name__ == "__main__":
main()

附录3:通过 PHP 连接数据库(NTS)

依赖环境

依赖环境:PHP 7.4版本及以上。
PHP 扩展(必需):
ext-openssl(用于加密解密)。
ext-json(用于 JSON 处理)。
ext-shmop(必需,用于 Token 缓存)。
1. 使用前需要在控制台 启用 CAM 验证
2. 在腾讯云控制台,账号信息 页面,查询账号的 APPID。
3. 访问管理控制台 > API 密钥管理 获取 SecretID 和 SecretKey。
注意:
进程管理:
所有平台(Windows/Linux/macOS):使用proc_open()实现后台定时器进程。
清空共享内存:
在启动进程时:需要调用DBAuthentication::clearCache()清空共享内存,避免访问到过期的 token。
Token 缓存(必需):
必须安装 shmop 扩展用于 Token 缓存。
用于实现跨进程 Token 共享(大幅提升性能,避免重复请求 CAM 服务)。
Windows、Linux 和 macOS 均支持。

使用

安装 SDK
composer require tencentcloud/dbauth-sdk-php
安装 PHP 扩展(必需)
必须安装 shmop 扩展用于 Token 缓存:
注意:
shmop 扩展是必需的,如果未安装,SDK 将无法正常工作。
Linux(Ubuntu/Debian)
# shmop 通常已内置在 PHP 中,验证是否已启用
php -m | grep shmop

# 如果未启用,需要重新编译 PHP 并添加 --enable-shmop 选项
# 或安装包含 shmop 的 PHP 包
sudo apt-get update
sudo apt-get install php-common

# 重启 PHP-FPM
sudo systemctl restart php-fpm
macOS
# shmop 通常已内置在 PHP 中,验证是否已启用
php -m | grep shmop

# 如果未启用,可能需要在 php.ini 中启用
# 或通过 Homebrew 重新安装 PHP
brew reinstall php

# 如果使用 PHP-FPM
brew services restart php
Windows
# shmop 通常已内置在 PHP 中,验证是否已启用
php -m | grep shmop

# 如果未启用,在 php.ini 中取消注释或添加:
extension=shmop

# 重启 Web 服务器
配置(php.ini)
extension=shmop ; 启用 shmop 扩展

重要注意事项

在使用 SDK 之前,请注意以下重要步骤:
1. 进程启动时:调用 DBAuthentication::clearCache() 清空共享内存,避免访问到过期的 token。
2. 进程结束时:调用 TencentCloud\\DBAuth\\Internal\\TimerManager::cancelAllTimers() 正确清理定时器资源。

使用 PHP 连接数据库示例

<?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 messages
error_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 logging
date_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 token
return 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 memory
DBAuthentication::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 second
sleep(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());
}

附录5:通过 .NET 连接数据库

依赖环境

依赖环境:.NET 6.0及以上版本。
1. 使用前需要在控制台 启用 CAM 验证
2. 在腾讯云控制台,账号信息 页面,查询账号的 APPID。
3. 访问管理控制台 > API 密钥管理 获取 SecretID 和 SecretKey。

间接依赖

需要 TencentCloudSDK v3.0.1374及以上版本。
说明:
版本号统一在 Directory.Build.props 文件中管理。更新依赖时,请修改该文件中的版本属性,以确保所有项目的版本一致性。

使用

dotnet add package TencentCloudSDK --version 3.0.1374

日志配置

如需打印 SDK 的相关日志,请在初始化时调用DBAuthentication.SetLoggerFactory(loggerFactory),传入 ILoggerFactory 实例:
using var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddConsole().SetMinimumLevel(LogLevel.Information);
});

DBAuthentication.SetLoggerFactory(loggerFactory);

使用 .NET 连接数据库示例

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 parameters
const 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 database
TestSqlServerConnection(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 mechanism
for (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;
}
}
}