Item | Description/Rule |
Connection method | Persistent connections should be used to access the database if possible. |
Enabling prerequisite | Before CAM authentication is enabled, it is required to configure the related permission policies in Tencent Cloud CAM in advance. |
Number of accounts | For a single database instance, it is recommended to enable CAM authentication for no more than 10 accounts. |
Password modification | After CAM authentication is enabled, the account password cannot be modified. You can only access the instances through using the token provided by CAM. |
Instance type | It is not supported to enable CAM authentication for instances with "password-free authentication" enabled. |
Disabling operation | To disable CAM authentication, a new static password should be set for the account; otherwise, databases cannot be connected. |
Version description | MongoDB 4.4 and later versions are supported, and CAM authentication is compatible with both the physical disk and Cloud Disk Edition simultaneously. |
{"statement": [{"action": ["cam:GetMongoDBPassword"],"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 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 "";}}
<dependency><groupId>org.mongodb</groupId><artifactId>mongodb-driver-sync</artifactId><version>4.11.0</version></dependency>
import com.mongodb.client.MongoClient;import com.mongodb.client.MongoClients;import com.mongodb.client.MongoDatabase;public class MongoDBConnectExample {public static void main(String[] args) {// Connection string format.String connectionString = "mongodb://<Account name>:<Password>@localhost:27017/<Database name>?authSource=admin";try (MongoClient mongoClient = MongoClients.create(connectionString)) {MongoDatabase database = mongoClient.getDatabase("<Database name>");System.out.println("Connected to MongoDB successfully!");// You can use the database to perform subsequent operations.} catch (Exception e) {e.printStackTrace();}}}
import loggingimport osimport timefrom pymongo import MongoClientfrom 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 logger.logging.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 = "cmgo-xxxx" # MongoDB instance ID.user_name = "camtest"host = "10.0.0.1"port = 27017db_name = "test"secret_id = os.environ['AK']secret_key = os.environ['SK']client = Nonetry:# Obtain a MongoDB connection.client = get_mongo_connection_using_cam(secret_id, secret_key, region,instance_id, user_name, host, port, db_name)# Verify whether the connection is successful.db = client[db_name]# Query test.dummy_collections = db.list_collection_names()log.info(f"Collections: {dummy_collections}")log.info("Success!")except Exception as e:log.error(f"An error occurred: {e}")finally:if client:client.close()def get_mongo_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 string format for MongoDB.mongo_uri = (f"mongodb://{user_name}:{auth_token}@{host}:{port}/{db_name}?authSource={db_name}")client = MongoClient(mongo_uri, serverSelectionTimeoutMS=5000)# Test the connection.client.admin.command("ping")return clientexcept Exception as e:last_exception = elog.info(f"Attempt {attempt} failed: {e}")time.sleep(5)log.error(f"All attempts failed: {last_exception}")raise last_exceptiondef get_auth_token(region, instance_id, user_name, cred):try:http_profile = HttpProfile()http_profile.endpoint = "cam.tencentcloudapi.com"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)return DBAuthentication.generate_authentication_token(request)except TencentCloudSDKException as err:log.error(err)raiseif __name__ == "__main__":main()
Feedback