Skip to content

TencentCloud/dbauth-sdk-php-zts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Language : 🇺🇸 | 🇨🇳

Tencent Cloud DBAuth SDK

Welcome to the Tencent Cloud DBAuth SDK, which provides developers with supporting development tools to access the Tencent Cloud Database CAM verification service, simplifying the access process of the Tencent Cloud Database CAM verification service.

Dependency Environment

  1. Dependency Environment: PHP 7.2 and above.
  2. PHP Extensions (Required):
    • ext-openssl (for encryption/decryption)
    • ext-json (for JSON processing)
    • ext-parallel (for high-performance async timers, requires ZTS PHP)
    • ext-apcu (for shared memory token caching across processes)
  3. Before use, CAM verification must be enabled on the Tencent Cloud console.
  4. On the Tencent Cloud console, view the account APPID on the account information page, and obtain the SecretID and SecretKey on the access management page.

Note:

  • Timer Implementation:

    • Uses parallel extension for high-performance async timers
    • Modern PHP 8.x compatible threading solution
    • Requires: ZTS PHP + parallel extension
  • Token Caching:

    • Uses APCu for shared memory caching across processes (required)
    • Automatic cleanup of expired tokens

USAGE

Install SDK

composer require tencentcloud/dbauth-sdk-php

Install PHP Extensions (Required)

parallel Extension (Required - High-Performance Async Timers)

You must install the parallel extension to support auto-refresh functionality:

# 1. Install ZTS PHP (Thread Safe)
# Ubuntu/Debian:
sudo apt-get install php-zts php-dev

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

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

# 2. Install parallel extension
pecl install parallel

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

# 4. Verify installation
php -m | grep parallel
php -i | grep "Thread Safety"  # Should show "enabled"

APCu Extension (Required - Shared Memory Token Caching)

APCu extension is required for shared memory token caching across processes:

# Install APCu extension
pecl install apcu

# Enable in php.ini
echo "extension=apcu.so" >> $(php -i | grep 'Loaded Configuration' | awk '{print $NF}')
echo "apc.enable_cli=1" >> $(php -i | grep 'Loaded Configuration' | awk '{print $NF}')  # Required for CLI usage

# Verify installation
php -m | grep apcu

Indirect Dependencies

For tencentcloud/tencentcloud-sdk-php and above.

Important Notes

Timer Thread Management

Due to the use of parallel extension's async timer functionality, timer threads must be manually cleaned up when the process ends:

// Call before application exits to ensure all timer threads exit correctly
\TencentCloud\DBAuth\Internal\TimerManager::cancelAllTimers();

Why manual call is required?

  • Threads created by the parallel extension do not automatically exit with the main process
  • If not manually canceled, timer threads will continue running, potentially causing resource leaks

Example - Connect to a Database Instance

<?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 parameters for Authentication Token
$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");

// Get the connection
$connection = getDBConnectionUsingCam($ak, $sk, $region, $instanceId, $userName, $host, $port, $dbName);

// Verify the connection is successful
$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 when process ends to ensure threads exit correctly
\TencentCloud\DBAuth\Internal\TimerManager::cancelAllTimers();

// Get a database connection using CAM Database Authentication
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 {
            // Get the authentication token using the credentials
            $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 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;
}

// Get an authentication token
function getAuthToken($region, $instanceId, $userName, $credential) {
    // Instantiate a client profile, optional, can be skipped if there are no special requirements
    $httpProfile = new HttpProfile();
    $httpProfile->setEndpoint("cam.tencentcloudapi.com");
    
    $clientProfile = new ClientProfile();
    $clientProfile->setHttpProfile($httpProfile);
    
    // Create a GenerateAuthenticationTokenRequest object, ClientProfile is optional
    $request = GenerateAuthenticationTokenRequest::builder()
        ->region($region)
        ->instanceId($instanceId)
        ->userName($userName)
        ->credential($credential)
        ->clientProfile($clientProfile)
        ->build();

    return DBAuthentication::generateAuthenticationToken($request);
}

Error Codes

Refer to the error code document for more information.

Limitations

There are some limitations when you use CAM database authentication. The following is from the CAM authentication documentation.

When you use CAM database authentication, your application must generate an CAM authentication token. Your application then uses that token to connect to the DB instance or cluster.

We recommend the following:

  • Use CAM database authentication as a mechanism for temporary, personal access to databases.
  • Use CAM database authentication only for workloads that can be easily retried.

About

dbauth-sdk-php-zts腾讯云数据库CAM验证SDK

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors