{"version": "2.0","statement": [{"effect": "allow","action": ["cam:BuildDataFlowAuthToken"],"resource": ["qcs::cam::uin/<User uin>:resourceUser/<Instance ID>/<Account name>"]}]}




<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 = "<Account name>";// 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 "";}}
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 variables required for the connection.String region = "ap-guangzhou";String instanceId = "cynosdb-123456";String userName = "test";String host = "192.*.*.11";int port = 3306;String dbName = "mysql";String secretId = System.getenv("TENCENTCLOUD_SECRET_ID");String secretKey = System.getenv("TENCENTCLOUD_SECRET_KEY");// Obtain a 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); // It should print "Success!"}// Close the connection.stmt.close();connection.close();}/*** Obtain a database connection using CAM database authentication.** @param secretId The secret ID.* @param secretKey The secret key.* @param region The region.* @param instanceId The instance ID.* @param userName The username.* @param host The host.* @param port The port.* @param dbName The database name.* @return The Connection object.* @throws Exception An exception.*/private static Connection getDBConnectionUsingCAM(String secretId, String secretKey, String region, String instanceId, String userName,String host, int port, String dbName) throws Exception {// Obtain credentials from the secretId and 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 {// Obtain 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;}/*** Obtain an authentication token.** @param region The region.* @param instanceId The instance ID.* @param userName The username.* @param credential The credential.* @return The authentication token.*/private static String getAuthToken(String region, String instanceId, String userName, Credential credential) throws TencentCloudSDKException {// 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);}}

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 the 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 = "cynosdb-123456"user_name = "camtest"host = "192.*.*.11"port = 3306db_name = "test"secret_id = os.environ['AK']secret_key = os.environ['SK']connection = Nonetry:# Obtain a connectionconnection = 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]) # It should print "Success!"except 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 (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()

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 parameters.region := "ap-guangzhou"instanceId := "cynosdb-123456"userName := "camtest"host := "192.*.*.11"port := 3306dbName := "test"ak := os.Getenv("TENCENTCLOUD_SECRET_ID")sk := os.Getenv("TENCENTCLOUD_SECRET_KEY")// Obtain a connection.connection, err := getDBConnectionUsingCam(ak, sk, region, instanceId, userName, host, port, dbName)if err != nil {logrus.Error("Failed to get connection:", err)return}// Verify whether the connection is successful.stmt, 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!}// Close the connection.if 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)}}// Obtain a database connection using CAM.func 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++ {// Obtain an authentication Token.authToken, 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}// Obtain an authentication Token.func getAuthToken(region, instanceId, userName string, credential *common.Credential) (string, error) {// Instantiate a client option (optional). Skip it if there are no special requirements.cpf := profile.NewClientProfile()cpf.HttpProfile.Endpoint = "cam.tencentcloudapi.com"// Create a GenerateAuthenticationTokenRequest object. The ClientProfile is optional.tokenRequest, 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)}
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