tencent cloud

TencentDB for SQL Server

Setting Account CAM Verification

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2026-04-28 10:53:18
This document describes how to configure CAM authentication for an account through the console.
Note:
If you need to enable CAM authentication for your account, submit a ticket to apply for whitelist access.

Background

In cloud database scenarios, you typically need to create separate accounts and passwords for the database and grant access and operation permissions to relevant users. This method of account management is complex and prone to security issues such as credential leakage. To address this, TencentDB for SQL Server supports enabling the CAM authentication feature for accounts. By linking Tencent Cloud sub-accounts with database accounts and adding CAM credential-based identity verification, it simplifies the complexity of account permission management, enhancing both database security and account management efficiency.

Scenarios

If you have high security requirements, you can use this feature to bind CAM to database account authentication. When making a request, you can obtain the corresponding password 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.

Note

Use long-lived connections to access the database whenever possible.
Before enabling CAM authentication, you must configure the relevant CAM permission rules in advance.
Password modification is not supported after CAM authentication is enabled.
After you disable CAM authentication, you cannot obtain access credentials through CAM. Therefore, you must enter a new password when disabling CAM authentication.

Feature Limitations

It is recommended that no more than 10 accounts have CAM authentication enabled within a single instance.
Password reset operations are not supported for the account after CAM authentication is enabled.
The CAM authentication feature can only be enabled for accounts associated with a single host address.
The CAM authentication feature cannot be enabled repeatedly for the same account name.
The CAM authentication feature cannot be enabled for the root account.

Prerequisites

The ticket has been submitted to apply for this feature.
The instance status is Running.

Step 1: Configuring CAM Permission Rules

Before using the account CAM authentication feature, you must configure the relevant CAM permission rules.

Policy Content

{
"statement": [
{
"action": [
"cam:BuildDataFlowAuthToken"
],
"effect": "allow",
"resource": [
"qcs::cam::uin/<User uin>:resourceUser/<Instance ID>/<Username>",
]
}
],
"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.
<Username>: Replace it with the actual username that needs to be authorized.

Operation Guide

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

Effect: Allow
Service: Cloud Access Management (CAM)
Action: Others - BuildDataFlowAuthToken
Resource: Specific resources - Add a six-segment resource description
Enter 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: Enabling CAM Authentication During Account Creation
Scenario 2: Enabling CAM Authentication for an Existing Account
2. On the instance list, click Instance ID or Manage in the Operation column to go to the instance management page.
3. On the instance management page, choose Account Management > Create Account, enter relevant information in the pop-up dialog box, and click OK after verification.
Note:
For the operation guide on creating accounts with different permissions, see Account Management. Only the steps related to enabling CAM authentication are introduced below.
Enable CAM Authentication: Turn on the button labeled "Enable CAM Authentication", read the important note in the pop-up window, and then click OK.
2. On the instance list, click Instance ID or Manage in the Operation column to go to the instance management page.
3. On the instance management page, select Account Management.
4. On the account management page, locate the target account and click Enable CAM Verificatipn in its operation column.
5. After reading the important note in the pop-up window, click OK.

Step 3: Obtaining the Password via Code Invocation in the Application

After assigning the related CAM permission policies and enabling CAM authentication for an account, users can obtain a password through calling code, such as Java, at the application side to establish connections to the database instance.
1. In the Tencent Cloud console, query the account AppID on the account information page.

2. Obtain the SecretID and SecretKey in CAM Console > API Key Management.
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 = "<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 "";
}
}
<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.
<Username>: Replace it with the actual username used for login.
<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: Connecting to TencentDB for SQL Server Using an Identity Token.

Note:
Using the JDBC driver for connection is the standard method for Java applications to connect to relational databases. For detailed JDBC driver installation and connection methods, see Using the JDBC Driver.
After the authentication token (AuthToken) is obtained in Step 3, you can use it to connect to TencentDB for SQL Server. The following connection command is a sample for connecting to the database using JDBC.
String connectionUrl = "jdbc:sqlserver://localhost:1433;databaseName=<Database name>;user=<Username>;password=<Password>;encrypt=false;";
Connection con = DriverManager.getConnection(connectionUrl);
<Database name>: Replace it with the actual name of the database that needs to be accessed.
<Username>: Replace it with the actual username you use to log in.
<Password>: Replace it with the AuthToken obtained in Step 3.

Refreshing the Password

After the CAM authentication feature is enabled for an account, you can update the password by refreshing it. If the account's rotation cycle is set to change the password every 12 hours, you can immediately update the password by refreshing it before the rotation cycle is reached.
Note:
Note that after you refresh the password, the current login credentials will become invalid. You need to observe whether the database access status of your business meets expectations.
2. On the instance list, click Instance ID or Manage in the Operation column to go to the instance management page.
3. On the instance management page, select Account Management.
4. On the account management page, locate the target account and click Reset Password in its operation column.
5. After reading the risk note in the pop-up window, click OK.

Disabling CAM Verification

Note:
After you disable CAM authentication, you cannot obtain access credentials through CAM. Please update your password promptly.
2. On the instance list, click Instance ID or Manage in the Operation column to go to the instance management page.
3. On the instance management page, select Account Management.
4. On the account management page, locate the target account and click Disable CAM Verification in its operation column.
5. In the pop-up window, enter and confirm the new password, then click OK.

Appendix 1: Error Codes

If the returned result contains an Error field, it indicates that the API call failed. For error code descriptions, see Error Codes.
The error codes related to the TencentDB for SQL Server account CAM authentication feature are as follows:

Note:

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
The request is not authorized. See the description of authentication in the CAM documentation.

Business Error Codes

Error Code
Description
FailedOperation.BuildAuthToken
AuthToken generation exception.
FailedOperation.FlowAuthIllegal
Credential 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. In the CAM Console > API Key Management, obtain the SecretID and SecretKey.
3. Install the TencentDB CAM Python SDK into your project using pip. Run the following command in the command line:
pip install git+https://github.com/TencentCloud/dbauth-sdk-python.git
Note that if both Python 2 and Python 3 environments are present, you must use the pip3 command for installation in the Python 3 environment.
Indirect dependency item: tencentcloud-sdk-python 3.0.1224 or later versions.

Example: Connecting to a Database Using 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

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

connection = None
try:
# 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 = 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:
# 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: Connecting to a Database Using PHP (NTS)

Dependencies

Dependency environment: PHP version 7.4 or later.
PHP extensions (required):
ext-openssl (used for encryption and decryption).
ext-json (used for JSON processing).
ext-shmop (required, used for Token caching).
1. Before use, you need to enable CAM authentication in the console.
2. In the Tencent Cloud console, query the account AppID on the account information page.
3. In the CAM Console > API Key Management, obtain the SecretID and SecretKey.
Note:
Process Management:
All platforms (Windows/Linux/macOS): Use proc_open() to implement the background timer process.
Clear shared memory:
When starting the process, you need to call DBAuthentication::clearCache() to clear the shared memory, preventing access to expired tokens.
Token caching (required):
The shmop extension must be installed for Token caching.
Used to implement cross-process Token sharing (significantly improving performance and avoiding repeated requests to the CAM service).
It is supported on Windows, Linux, and macOS.

Usage

Installing the SDK
composer require tencentcloud/dbauth-sdk-php
Install PHP extensions (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 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 update
sudo apt-get install php-common

# Restart PHP-FPM
sudo systemctl restart php-fpm
macOS
# 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-FPM
brew services restart php
Windows
# 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.
Configure (php.ini)
extension=shmop ; Enable the shmop extension

Important Notes

Before the SDK is used, note the following important steps:
1. When the process starts: Call DBAuthentication::clearCache() to clear the shared memory, preventing access to expired tokens.
2. When the process ends: Call TencentCloud\\DBAuth\\Internal\\TimerManager::cancelAllTimers() to properly clean up timer resources.

Example: Connecting to a Database Using 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());
}

Appendix 5: Connecting to a Database Using .NET

Dependencies

Dependency environment: .NET version 6.0 or later.
1. Before use, you need to enable CAM authentication in the console.
2. In the Tencent Cloud console, query the account AppID on the account information page.
3. In the CAM Console > API Key Management, obtain the SecretID and SecretKey.

Indirect Dependencies

Requires TencentCloudSDK version 3.0.1374 or later.
Note:
Version numbers are uniformly managed in the Directory.Build.props file. When dependencies are updated, modify the version properties in this file to ensure version consistency across all projects.

Usage

dotnet add package TencentCloudSDK --version 3.0.1374

Log configuration

To print SDK-related logs, call 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);

Example: Connecting to a Database Using .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;
}
}
}


Ajuda e Suporte

Esta página foi útil?

comentários