{"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 the parameters for an authentication token.String region = "Instance region";String instanceId = "Instance ID";String userName = "Account Name";// Get the credentials from an environment variable.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 profile, which is optional and can be skipped if there are no special requirements.HttpProfile httpProfile = new HttpProfile();httpProfile.setEndpoint("cam.tencentcloudapi.com");// Instantiate a client profile, which is optional and can be skipped if there are no special requirements.ClientProfile clientProfile = new ClientProfile();clientProfile.setHttpProfile(httpProfile);// Build a 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 necessary variables 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");// Get the 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); // "Success!" should be printed.}// Close the connection.stmt.close();connection.close();}/*** Get the database connection using CAM database authentication.** @param secretId Secret key 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 {// Get the credentials from a secretId and a secretKey.Credential credential = new Credential(secretId, secretKey);// Define the maximum number of attempts.int maxAttempts = 3;Exception lastException = null;for (int attempt = 1; attempt <= maxAttempts; attempt++) {try {// Get an authentication token using the credentials.String 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;}/*** Get 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 profile, which is optional and can be skipped if there are no special requirements.HttpProfile httpProfile = new HttpProfile();httpProfile.setEndpoint("cam.tencentcloudapi.com");// Instantiate a client profile, which is optional and can be skipped if there are no special requirements.ClientProfile clientProfile = new ClientProfile();clientProfile.setHttpProfile(httpProfile);// Build a 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 Authorization in the request header does not meet Tencent Cloud standards. |
AuthFailure.InvalidSecretId | Invalid key (not a TencentCloud API key type). |
AuthFailure.MFAFailure | |
AuthFailure.SecretIdNotFound | The key does not exist. Please check whether the key has been deleted or disabled in the console, and if not, check whether the key is entered correctly. Ensure no spaces before or after the key. |
AuthFailure.SignatureExpire | Signature expired. The time difference between the timestamp and the server time cannot exceed five minutes. Please ensure the local time matches the standard time. |
AuthFailure.SignatureFailure | Invalid signature. Signature calculation error. Please ensure you have followed the signature calculation process as described in the signature algorithm documentation for the calling method. |
AuthFailure.TokenFailure | Token error. |
AuthFailure.UnauthorizedOperation | The request is not authorized. Please refer to the CAM documentation for the authentication instructions. |
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 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:# Get the connectionconnection = get_db_connection_using_cam(secret_id, secret_key, region,instance_id, user_name, host, port, db_name)# Verify if the connection is successfulwith connection.cursor() as cursor:cursor.execute("SELECT 'Success!';")result = cursor.fetchone()log.info(result[0]) # "Success!" should be printedexcept 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, which is optional and can be skipped without specific requirementshttp_profile = HttpProfile()http_profile.endpoint = "cam.tencentcloudapi.com"# Instantiate a client option, which is optional and can be skipped without specific requirementsclient_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")// Get the connection addressconnection, err := getDBConnectionUsingCam(ak, sk, region, instanceId, userName, host, port, dbName)if err != nil {logrus.Error("Failed to get connection:", err)return}// Verify if 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!}// Disable the connectionif 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 get a database connectionfunc 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++ {// Get 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}// Get an authentication tokenfunc getAuthToken(region, instanceId, userName string, credential *common.Credential) (string, error) {// Instantiate a client option, which is optional and can be skipped without specific requirementscpf := profile.NewClientProfile()cpf.HttpProfile.Endpoint = "cam.tencentcloudapi.com"// Create a GenerateAuthenticationTokenRequest object. ClientProfile is optionaltokenRequest, 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)}
Feedback