tencent cloud

Feedback

Setting Account CAM Verification

Last updated: 2024-11-11 17:27:12
    This document introduces the instructions and operations for setting account CAM verification through the console.
    Note:
    If you need to enable account CAM verification, submit a ticket to apply for the allowlist features.

    Supported Regions

    This feature is currently supported in the following regions: Shanghai and Guangzhou.

    Background

    In scenarios where cloud databases are used, it is often necessary to create separate accounts and passwords for the databases and grant access and operation permissions to corresponding users. This method of account management is complex and prone to security issues such as account and password leaks. Based on this background, TencentDB for MySQL supports the CAM verification feature for accounts. By connecting sub-accounts of Tencent Cloud platform with database accounts and adding CAM credential authentication, the complexity of account permission management is simplified, therefore enhancing database security and account management efficiency.

    Overview

    If you have high security requirements, you can use this feature to bind CAM with database accounts for verification. You can obtain the corresponding password when requesting to access the database, thereby enhancing database security. It is recommended that CAM verification be enabled in the following two scenarios.
    Using CAM verification as a verification mechanism for temporary, individual access to the database.
    Using CAM verification as a verification mechanism only for workloads that can be easily retried.

    Notes

    Use long connections to access the database whenever possible.
    Before enabling CAM verification, ensure that the related CAM permission rules are configured in advance.
    After enabling CAM verification, password changes are not supported.
    The root account also supports CAM verification.
    After disabling CAM verification, you will not be able to obtain access credentials through CAM. Therefore, you need to enter a new password when disabling CAM verification.

    Feature Limits

    It is recommended to enable CAM verification for no more than 10 accounts within a single instance.
    After CAM verification is enabled, the password reset operation for this account is not supported.
    Only an account with a single server address is supported to enable CAM verification.
    CAM verification cannot be enabled repeatedly for the same account.
    If the instance has been enabled with CAM verification, the password complexity feature cannot be enabled.
    If the instance has been enabled with the password complexity feature, the password complexity rules cannot be adjusted after CAM verification is enabled.

    Prerequisites

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

    Step 1: Configuring CAM Permission Rules

    Before using the CAM verification feature with the account, you need to configure the related CAM permission rules.

    Policy Content

    {
    "statement": [
    {
    "action": [
    "cam:BuildDataFlowAuthToken"
    ],
    "effect": "allow",
    "resource": [
    "qcs::cam::uin/<User uin>:resourceUser/<Instance ID>/<Account Name>",
    ]
    }
    ],
    "version": "2.0"
    }
    User uin: Replace with the actual account ID.
    Instance ID: Replace with the actual instance ID to be authorized.
    Account Name: Replace with the actual account name to be authorized.

    Operation Instructions

    1. Log in to the CAM console with the admin account. On the Policies page, create a custom policy using the Policy Generator (refer to Creating Custom Policy).
    
    Effect: Allow
    Service: Cloud Access Management (cam)
    Action: Others Edit > BuildDataFlowAuthToken
    Resource: Specific resources > Add a six-segment resource description
    Filling in resources: Instance ID/Account Name
    2. Click Next, name your custom policy, and assign the policy to the target sub-account.
    3. Click Complete to finish the authorization.

    Step 2: Enabling CAM Verification

    There are two scenarios for enabling CAM verification: enabling CAM verification when creating an account and enabling CAM verification for an existing account. You can follow the steps below for each scenario.
    Scenario 1: Enabling CAM verification when creating an account
    Scenario 2: Enabling CAM verification for an existing account
    1. Log in to the TencentDB for MySQL console.
    2. In the instance list, click Instance ID or click Manage in the Operation column to enter the instance management page.
    3. On the instance management page, choose Database Management > Account Management > Create Account, enter relevant information in the pop-up window, and click OK after confirmation.
    Note:
    For detailed steps on creating an account, refer to Create Account. The following describes the steps related to enabling CAM verification.
    Enable CAM verification: Turn on the switch for "Enable CAM verification", read the important notice in the pop-up window, and click OK.
    4. For accounts that have been successfully enabled with CAM verification, "CAM verification enabled" will be displayed.
    1. Log in to the TencentDB for MySQL console.
    2. In the instance list, click Instance ID or click Manage in the Operation column to enter the instance management page.
    3. On the instance management page, choose Database Management > Account Management.
    4. On the account management page, find the target account and click Enable CAM Verification in its operations column.
    5. Read the important notice in the pop-up window, and then click OK.
    6. For accounts that have been successfully enabled with CAM verification, "CAM verification enabled" will be displayed.

    Step 3: Obtaining the Password Through Code Calling in the Application

    Once the account has the relevant CAM permission specifications and CAM verification is enabled, you can obtain the password through code calling in Java or other languages in the application to connect to the database instance. You can also use Python to establish a connection with the database instances. For detailed instructions, refer to Appendix 4: Connecting to Databases via Python.
    1. In the Tencent Cloud console, query the APPID of the account on the Account Information page.
    
    2. Obtain the SecretID and SecretKey in CAM Console > API Key Management.
    3. Use the following code in the application.
    <dependency>
    <groupId>com.tencentcloudapi</groupId>
    <artifactId>tencentcloud-dbauth-sdk-java</artifactId>
    <version>1.0.4</version>
    </dependency>
    Indirect dependency: 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 the password through code calling
    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 "";
    }
    }
    Instance region: Replace with the region of the instance you need to access, for example, ap-guangzhou.
    Instance ID: Replace with the ID of the instance you need to access.
    Account Name: Replace with the actual account name to log in.
    TENCENTCLOUD_SECRET_ID: Replace with the SecretID obtained from the CAM console.
    TENCENTCLOUD_SECRET_KEY: Replace with the SecretKey obtained from the CAM console.

    Step 4: Using the Identity Token to Connect to TencentDB for MySQL

    After obtaining the identity token AuthToken in Step 3, you can use it to connect to TencentDB for MySQL, as shown below.
    mysql --host=<IP address> --port=<Port number> --user=<Account Name> --password=<Password>;
    IP address: Replace with the IP address of your instance.
    Port number: Replace with the port number of your instance. If the port is not modified, the port number is 3306 by default.
    Account Name: Replace with the actual account name to log in.
    Password: Replace with the AuthToken obtained in Step 3.

    An Example of Connecting to a Database Using Java Code

    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);
    }
    }

    Appendix 1: Resetting Password

    When the CAM verification feature is enabled for the account, you can update the password through the password reset operation. If the account is set to change the password every 12 hours for the rotation cycle, you can immediately update the password by performing the password reset operation before the rotation cycle is reached.
    Note:
    Note that the current login credentials will become invalid after the password is reset. You need to check whether the database access status meets expectations.
    1. Log in to the TencentDB for MySQL console.
    2. In the instance list, click Instance ID or click Manage in the Operation column to enter the instance management page.
    3. On the instance management page, choose Database Management > Account Management.
    4. On the account management page, find the target account, and in its operations column, choose More > Reset Password.
    5. Read the risk warning in the pop-up window, and then click OK.

    Appendix 2: Disabling CAM Verification

    Note:
    After disabling CAM verification, you will not be able to obtain access credentials through CAM. Please update your password promptly.
    1. Log in to the TencentDB for MySQL console.
    2. In the instance list, click Instance ID or click Manage in the Operation column to enter the instance management page.
    3. On the instance management page, choose Database Management > Account Management.
    4. On the account management page, find the target account and in its operations column, choose More > Disable CAM Verification.
    5. In the pop-up window, enter the new password and confirm the password, and then click OK.

    Appendix 3: Error Codes

    If the returned result contains an Error field, it indicates that the API call failed. For information on error codes, please refer to Error Codes.
    The following are the error codes related to the CAM verification feature for accounts of TencentDB for MySQL:

    Common Error Codes

    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
    MFA error.
    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.

    Business Error Codes

    Error Code
    Description
    FailedOperation.BuildAuthToken
    AuthToken generation exception.
    FailedOperation.FlowAuthIllegal
    Credential operation failed.
    Contact Us

    Contact our sales team or business advisors to help your business.

    Technical Support

    Open a ticket if you're looking for further assistance. Our Ticket is 7x24 avaliable.

    7x24 Phone Support