{"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. |
Was this page helpful?