本页显示了支持的身份验证方法和客户端,还演示了可用于使用服务连接器将 Azure Cosmos DB for MongoDB 连接到其他云服务的示例代码。 即使不使用服务连接器,你可能仍然可以使用其他编程语言连接到 Azure Cosmos DB for MongoDB。 此页面还显示了你在创建服务连接时获得的默认环境变量名称和值(或 Spring Boot 配置)。
受支持的计算服务
服务连接器可用于将以下计算服务连接到 Azure Cosmos DB for MongoDB:
- Azure 应用程序服务
- Azure Container Apps
- Azure Functions
- Azure Kubernetes 服务 (AKS)
- Azure Spring Apps
受支持的身份验证类型和客户端类型
下表显示了使用服务连接器将计算服务连接到 Azure Cosmos DB for MongoDB 时支持哪些客户端类型和身份验证方法的组合。 “是”表示支持该组合,“否”表示不支持该组合。
客户端类型 |
系统分配的托管标识 |
用户分配的托管标识 |
机密/连接字符串 |
服务主体 |
.NET |
是 |
是 |
是 |
是 |
Java |
是 |
是 |
是 |
是 |
Java - Spring Boot |
否 |
No |
是 |
否 |
Node.js |
是 |
是 |
是 |
是 |
Python |
是 |
是 |
是 |
是 |
Go |
是 |
是 |
是 |
是 |
无 |
是 |
是 |
是 |
是 |
此表指示支持客户端类型和身份验证方法的所有组合,但 Java - Spring Boot 客户端类型除外,它们仅支持机密/连接字符串方法。 所有其他客户端类型都可通过服务连接器使用任何身份验证方法连接到 Azure Cosmos DB for MongoDB。
默认环境变量名称或应用程序属性和示例代码
使用以下连接详细信息将计算服务连接到 Azure Cosmos DB。 本页还显示了你在创建服务连接时获得的默认环境变量名称和值(或 Spring Boot 配置)以及示例代码。 对于下面每个示例,请将占位符文本 <mongo-db-admin-user>
、<password>
、<Azure-Cosmos-DB-API-for-MongoDB-account>
、<subscription-ID>
、<resource-group-name>
、<client-secret>
和 <tenant-id>
替换为你自己的信息。 有关命名约定的详细信息,请参阅服务连接器内部一文。
系统分配的托管标识
默认环境变量名称 |
说明 |
示例值 |
AZURE_COSMOS_LISTCONNECTIONSTRINGURL |
用户获取连接字符串的 URL |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-API-for-MongoDB-account>/listConnectionStrings?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
托管标识范围 |
https://management.azure.com/.default |
AZURE_COSMOS_RESOURCEENDPOINT |
资源终结点 |
https://<Azure-Cosmos-DB-API-for-MongoDB-account>.documents.azure.com:443/ |
代码示例
请参阅下面的步骤和代码,使用系统分配的托管标识连接到 Azure Cosmos DB for MongoDB。
安装依赖项
dotnet add package MongoDb.Driver
dotnet add package Azure.Identity
使用 Azure.Identity 客户端库获取托管标识或服务主体的访问令牌。 使用访问令牌和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using MongoDB.Driver;
using Azure.Identity;
using System.Text.Json;
// you can retrieve the endpoint of the resource with the following env variable:
// Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var listConnectionStringUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// var tokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var tokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID")
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
// var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await tokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]{ scope }));
// Get the connection string.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.PostAsync(new Uri(listConnectionStringUrl), null);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
var connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
将以下依赖项添加到 pom.xml 文件:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
使用 azure-identity
获取托管标识或服务主体的访问令牌。 使用访问令牌和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
import java.net.URI;
String endpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listConnectionStringUrl = System.getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
// For user assigned managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
// .managedIdentityClientId(System.getenv("AZURE_COSMOS_CLIENTID"))
// .build();
// For service principal.
// ClientSecretCredential defaultCredential = new ClientSecretCredentialBuilder()
// .clientId(System.getenv("<AZURE_COSMOS_CLIENTID>"))
// .clientSecret(System.getenv("<AZURE_COSMOS_CLIENTSECRET>"))
// .tenantId(System.getenv("<AZURE_COSMOS_TENANTID>"))
// .build();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the connection string.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listConnectionStringUrl))
.header("Authorization", "Bearer " + token)
.POST()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONParser parser = new JSONParser();
JSONObject responseBody = parser.parse(response.body());
List<Map<String, String>> connectionStrings = responseBody.get("connectionStrings");
String connectionString = connectionStrings.get(0).get("connectionString");
// Connect to Azure Cosmos DB for MongoDB
MongoClientURI uri = new MongoClientURI(connectionString);
MongoClient mongoClient = new MongoClient(uri);
安装依赖项。
pip install pymongo
pip install azure-identity
在代码中,通过 azure-identity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import os
import pymongo
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT')
listConnectionStringUrl = os.getenv('AZURE_COSMOS_LISTCONNECTIONSTRINGURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity
# cred = ManagedIdentityCredential()
# For user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_COSMOS_TENANTID')
# client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# client_secret = os.getenv('AZURE_COSMOS_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Get the connection string
session = requests.Session()
token = cred.get_token(scope)
response = session.post(listConnectionStringUrl, headers={"Authorization": "Bearer {}".format(token.token)})
keys_dict = response.json()
conn_str = keys_dict["connectionStrings"][0]["connectionString"]
# Connect to Azure Cosmos DB for MongoDB
client = pymongo.MongoClient(conn_str)
安装依赖项。
go get go.mongodb.org/mongo-driver/mongo
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在代码中,通过 azidentity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
endpoint = os.Getenv("AZURE_COSMOS_RESOURCEENDPOINT")
listConnectionStringUrl = os.Getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL")
scope = os.Getenv("AZURE_COSMOS_SCOPE")
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listConnectionStringUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
connectionString, err := result["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
clientOptions := options.Client().ApplyURI(connectionString).SetDirect(true)
c, err := mongo.Connect(ctx, clientOptions)
安装依赖项
npm install mongodb
npm install --save @azure/identity
在代码中,通过 @azure/identity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { MongoClient, ObjectId } = require('mongodb');
const axios = require('axios');
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let listConnectionStringUrl = process.env.AZURE_COSMOS_LISTCONNECTIONSTRINGURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_COSMOS_TENANTID;
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const clientSecret = process.env.AZURE_COSMOS_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken(scope);
// Get the connection string.
const config = {
method: 'post',
url: listConnectionStringUrl,
headers: {
'Authorization': `Bearer ${accessToken.token}`
}
};
const response = await axios(config);
const keysDict = response.data;
const connectionString = keysDict['connectionStrings'][0]['connectionString'];
const client = new MongoClient(connectionString);
用户分配的托管标识
默认环境变量名称 |
说明 |
示例值 |
AZURE_COSMOS_LISTCONNECTIONSTRINGURL |
用户获取连接字符串的 URL |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-API-for-MongoDB-account>/listConnectionStrings?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
托管标识范围 |
https://management.azure.com/.default |
AZURE_COSMOS_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_COSMOS_RESOURCEENDPOINT |
资源终结点 |
https://<Azure-Cosmos-DB-API-for-MongoDB-account>.documents.azure.com:443/ |
代码示例
请参考以下步骤和代码,使用用户分配的托管标识连接到 Azure Cosmos DB for MongoDB。
安装依赖项
dotnet add package MongoDb.Driver
dotnet add package Azure.Identity
使用 Azure.Identity 客户端库获取托管标识或服务主体的访问令牌。 使用访问令牌和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using MongoDB.Driver;
using Azure.Identity;
using System.Text.Json;
// you can retrieve the endpoint of the resource with the following env variable:
// Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var listConnectionStringUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// var tokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var tokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID")
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
// var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await tokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]{ scope }));
// Get the connection string.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.PostAsync(new Uri(listConnectionStringUrl), null);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
var connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
将以下依赖项添加到 pom.xml 文件:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
使用 azure-identity
获取托管标识或服务主体的访问令牌。 使用访问令牌和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
import java.net.URI;
String endpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listConnectionStringUrl = System.getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
// For user assigned managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
// .managedIdentityClientId(System.getenv("AZURE_COSMOS_CLIENTID"))
// .build();
// For service principal.
// ClientSecretCredential defaultCredential = new ClientSecretCredentialBuilder()
// .clientId(System.getenv("<AZURE_COSMOS_CLIENTID>"))
// .clientSecret(System.getenv("<AZURE_COSMOS_CLIENTSECRET>"))
// .tenantId(System.getenv("<AZURE_COSMOS_TENANTID>"))
// .build();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the connection string.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listConnectionStringUrl))
.header("Authorization", "Bearer " + token)
.POST()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONParser parser = new JSONParser();
JSONObject responseBody = parser.parse(response.body());
List<Map<String, String>> connectionStrings = responseBody.get("connectionStrings");
String connectionString = connectionStrings.get(0).get("connectionString");
// Connect to Azure Cosmos DB for MongoDB
MongoClientURI uri = new MongoClientURI(connectionString);
MongoClient mongoClient = new MongoClient(uri);
安装依赖项。
pip install pymongo
pip install azure-identity
在代码中,通过 azure-identity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import os
import pymongo
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT')
listConnectionStringUrl = os.getenv('AZURE_COSMOS_LISTCONNECTIONSTRINGURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity
# cred = ManagedIdentityCredential()
# For user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_COSMOS_TENANTID')
# client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# client_secret = os.getenv('AZURE_COSMOS_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Get the connection string
session = requests.Session()
token = cred.get_token(scope)
response = session.post(listConnectionStringUrl, headers={"Authorization": "Bearer {}".format(token.token)})
keys_dict = response.json()
conn_str = keys_dict["connectionStrings"][0]["connectionString"]
# Connect to Azure Cosmos DB for MongoDB
client = pymongo.MongoClient(conn_str)
安装依赖项。
go get go.mongodb.org/mongo-driver/mongo
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在代码中,通过 azidentity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
endpoint = os.Getenv("AZURE_COSMOS_RESOURCEENDPOINT")
listConnectionStringUrl = os.Getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL")
scope = os.Getenv("AZURE_COSMOS_SCOPE")
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listConnectionStringUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
connectionString, err := result["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
clientOptions := options.Client().ApplyURI(connectionString).SetDirect(true)
c, err := mongo.Connect(ctx, clientOptions)
安装依赖项
npm install mongodb
npm install --save @azure/identity
在代码中,通过 @azure/identity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { MongoClient, ObjectId } = require('mongodb');
const axios = require('axios');
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let listConnectionStringUrl = process.env.AZURE_COSMOS_LISTCONNECTIONSTRINGURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_COSMOS_TENANTID;
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const clientSecret = process.env.AZURE_COSMOS_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken(scope);
// Get the connection string.
const config = {
method: 'post',
url: listConnectionStringUrl,
headers: {
'Authorization': `Bearer ${accessToken.token}`
}
};
const response = await axios(config);
const keysDict = response.data;
const connectionString = keysDict['connectionStrings'][0]['connectionString'];
const client = new MongoClient(connectionString);
连接字符串
警告
Microsoft 建议使用最安全的可用身份验证流。 本过程中介绍的身份验证流程需要非常高的信任度,并携带其他流中不存在的风险。 请仅在无法使用其他更安全的流(例如托管标识)时才使用此流。
SpringBoot 客户端类型
默认环境变量名称 |
说明 |
示例值 |
spring.data.mongodb.database |
你的数据库 |
<database-name> |
spring.data.mongodb.uri |
你的数据库 URI |
mongodb://<mongo-db-admin-user>:<password>@<mongo-db-server>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@<mongo-db-server>@ |
其他客户端类型
默认环境变量名称 |
说明 |
示例值 |
AZURE_COSMOS_CONNECTIONSTRING |
MongoDB API 连接字符串 |
mongodb://<mongo-db-admin-user>:<password>@<mongo-db-server>.mongo.cosmos.azure.com:10255/?ssl=true&replicaSet=globaldb&retrywrites=false&maxIdleTimeMS=120000&appName=@<mongo-db-server>@ |
代码示例
请参考以下步骤和代码,使用连接字符串连接到 Azure Cosmos DB for MongoDB。
安装依赖项。
dotnet add package MongoDb.Driver
从服务连接器添加的环境变量中获取连接字符串,并连接到 Azure Cosmos DB for MongoDB。
using MongoDB.Driver;
var connectionString = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONNECTIONSTRING");
var client = new MongoClient(connectionString);
在 pom.xml 文件中添加以下依赖项:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
从服务连接器添加的环境变量中获取连接字符串,并连接到 Azure Cosmos DB for MongoDB。
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
String connectionString = System.getenv("AZURE_COSMOS_CONNECTIONSTRING");
MongoClientURI uri = new MongoClientURI(connectionString);
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient(uri);
} finally {
if (mongoClient != null) {
mongoClient.close();
}
}
安装依赖项。
pip install pymongo
从服务连接器添加的环境变量中获取连接字符串,并连接到 Azure Cosmos DB for MongoDB。
import os
import pymongo
conn_str = os.environ.get("AZURE_COSMOS_CONNECTIONSTRING")
client = pymongo.MongoClient(conn_str)
- 安装依赖项。
go get go.mongodb.org/mongo-driver/mongo
- 从服务连接器添加的环境变量中获取连接字符串,并连接到 Azure Cosmos DB for MongoDB。
import (
"context"
"fmt"
"log"
"os"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
mongoDBConnectionString = os.Getenv("AZURE_COSMOS_CONNECTIONSTRING")
clientOptions := options.Client().ApplyURI(mongoDBConnectionString).SetDirect(true)
c, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatalf("unable to initialize connection %v", err)
}
err = c.Ping(ctx, nil)
if err != nil {
log.Fatalf("unable to connect %v", err)
}
- 安装依赖项。
npm install mongodb
- 从服务连接器添加的环境变量中获取连接字符串,并连接到 Azure Cosmos DB for MongoDB。
const { MongoClient, ObjectId } = require('mongodb');
const url = process.env.AZURE_COSMOS_CONNECTIONSTRING;
const client = new MongoClient(url);
服务主体
默认环境变量名称 |
说明 |
示例值 |
AZURE_COSMOS_LISTCONNECTIONSTRINGURL |
用户获取连接字符串的 URL |
https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<Azure-Cosmos-DB-API-for-MongoDB-account>/listConnectionStrings?api-version=2021-04-15 |
AZURE_COSMOS_SCOPE |
托管标识范围 |
https://management.azure.com/.default |
AZURE_COSMOS_CLIENTID |
客户端 ID |
<client-ID> |
AZURE_COSMOS_CLIENTSECRET |
客户端密码 |
<client-secret> |
AZURE_COSMOS_TENANTID |
租户 ID |
<tenant-ID> |
AZURE_COSMOS_RESOURCEENDPOINT |
资源终结点 |
https://<Azure-Cosmos-DB-API-for-MongoDB-account>.documents.azure.com:443/ |
代码示例
请参考以下步骤和代码,使用服务主体连接到 Azure Cosmos DB for MongoDB。
安装依赖项
dotnet add package MongoDb.Driver
dotnet add package Azure.Identity
使用 Azure.Identity 客户端库获取托管标识或服务主体的访问令牌。 使用访问令牌和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
using System;
using System.Security.Authentication;
using System.Net.Security;
using System.Net.Http;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using MongoDB.Driver;
using Azure.Identity;
using System.Text.Json;
// you can retrieve the endpoint of the resource with the following env variable:
// Environment.GetEnvironmentVariable("AZURE_COSMOS_RESOURCEENDPOINT");
var listConnectionStringUrl = Environment.GetEnvironmentVariable("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
var scope = Environment.GetEnvironmentVariable("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// var tokenProvider = new DefaultAzureCredential();
// For user-assigned identity.
// var tokenProvider = new DefaultAzureCredential(
// new DefaultAzureCredentialOptions
// {
// ManagedIdentityClientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID")
// }
// );
// For service principal.
// var tenantId = Environment.GetEnvironmentVariable("AZURE_COSMOS_TENANTID");
// var clientId = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTID");
// var clientSecret = Environment.GetEnvironmentVariable("AZURE_COSMOS_CLIENTSECRET");
// var tokenProvider = new ClientSecretCredential(tenantId, clientId, clientSecret);
// Acquire the access token.
AccessToken accessToken = await tokenProvider.GetTokenAsync(
new TokenRequestContext(scopes: new string[]{ scope }));
// Get the connection string.
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {accessToken.Token}");
var response = await httpClient.PostAsync(new Uri(listConnectionStringUrl), null);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
var connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
将以下依赖项添加到 pom.xml 文件:
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
使用 azure-identity
获取托管标识或服务主体的访问令牌。 使用访问令牌和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
import java.net.URI;
String endpoint = System.getenv("AZURE_COSMOS_RESOURCEENDPOINT");
String listConnectionStringUrl = System.getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL");
String scope = System.getenv("AZURE_COSMOS_SCOPE");
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder().build();
// For user assigned managed identity.
// DefaultAzureCredential defaultCredential = new DefaultAzureCredentialBuilder()
// .managedIdentityClientId(System.getenv("AZURE_COSMOS_CLIENTID"))
// .build();
// For service principal.
// ClientSecretCredential defaultCredential = new ClientSecretCredentialBuilder()
// .clientId(System.getenv("<AZURE_COSMOS_CLIENTID>"))
// .clientSecret(System.getenv("<AZURE_COSMOS_CLIENTSECRET>"))
// .tenantId(System.getenv("<AZURE_COSMOS_TENANTID>"))
// .build();
// Get the access token.
AccessToken accessToken = defaultCredential.getToken(new TokenRequestContext().addScopes(new String[]{ scope })).block();
String token = accessToken.getToken();
// Get the connection string.
HttpClient client = HttpClient.newBuilder().build();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(listConnectionStringUrl))
.header("Authorization", "Bearer " + token)
.POST()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
JSONParser parser = new JSONParser();
JSONObject responseBody = parser.parse(response.body());
List<Map<String, String>> connectionStrings = responseBody.get("connectionStrings");
String connectionString = connectionStrings.get(0).get("connectionString");
// Connect to Azure Cosmos DB for MongoDB
MongoClientURI uri = new MongoClientURI(connectionString);
MongoClient mongoClient = new MongoClient(uri);
安装依赖项。
pip install pymongo
pip install azure-identity
在代码中,通过 azure-identity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import os
import pymongo
import requests
from azure.identity import ManagedIdentityCredential, ClientSecretCredential
endpoint = os.getenv('AZURE_COSMOS_RESOURCEENDPOINT')
listConnectionStringUrl = os.getenv('AZURE_COSMOS_LISTCONNECTIONSTRINGURL')
scope = os.getenv('AZURE_COSMOS_SCOPE')
# Uncomment the following lines corresponding to the authentication type you want to use.
# For system-assigned managed identity
# cred = ManagedIdentityCredential()
# For user-assigned managed identity
# managed_identity_client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# cred = ManagedIdentityCredential(client_id=managed_identity_client_id)
# For service principal
# tenant_id = os.getenv('AZURE_COSMOS_TENANTID')
# client_id = os.getenv('AZURE_COSMOS_CLIENTID')
# client_secret = os.getenv('AZURE_COSMOS_CLIENTSECRET')
# cred = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
# Get the connection string
session = requests.Session()
token = cred.get_token(scope)
response = session.post(listConnectionStringUrl, headers={"Authorization": "Bearer {}".format(token.token)})
keys_dict = response.json()
conn_str = keys_dict["connectionStrings"][0]["connectionString"]
# Connect to Azure Cosmos DB for MongoDB
client = pymongo.MongoClient(conn_str)
安装依赖项。
go get go.mongodb.org/mongo-driver/mongo
go get "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
go get "github.com/Azure/azure-sdk-for-go/sdk/azcore"
在代码中,通过 azidentity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
endpoint = os.Getenv("AZURE_COSMOS_RESOURCEENDPOINT")
listConnectionStringUrl = os.Getenv("AZURE_COSMOS_LISTCONNECTIONSTRINGURL")
scope = os.Getenv("AZURE_COSMOS_SCOPE")
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// cred, err := azidentity.NewDefaultAzureCredential(nil)
// For user-assigned identity.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// azidentity.ManagedIdentityCredentialOptions.ID := clientid
// options := &azidentity.ManagedIdentityCredentialOptions{ID: clientid}
// cred, err := azidentity.NewManagedIdentityCredential(options)
// For service principal.
// clientid := os.Getenv("AZURE_COSMOS_CLIENTID")
// tenantid := os.Getenv("AZURE_COSMOS_TENANTID")
// clientsecret := os.Getenv("AZURE_COSMOS_CLIENTSECRET")
// cred, err := azidentity.NewClientSecretCredential(tenantid, clientid, clientsecret, &azidentity.ClientSecretCredentialOptions{})
// Acquire the access token.
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
token, err := cred.GetToken(ctx, policy.TokenRequestOptions{
Scopes: []string{scope},
})
// Acquire the connection string.
client := &http.Client{}
req, err := http.NewRequest("POST", listConnectionStringUrl, nil)
req.Header.Add("Authorization", "Bearer " + token.Token)
resp, err := client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
var result map[string]interface{}
json.Unmarshal(body, &result)
connectionString, err := result["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
clientOptions := options.Client().ApplyURI(connectionString).SetDirect(true)
c, err := mongo.Connect(ctx, clientOptions)
安装依赖项
npm install mongodb
npm install --save @azure/identity
在代码中,通过 @azure/identity
获取访问令牌,然后使用它来获取连接字符串。 从服务连接器添加的环境变量中获取连接信息,并连接到 Azure Cosmos DB for MongoDB。 使用下面的代码时,请对要使用的身份验证类型的代码片段的一部分取消评论。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { MongoClient, ObjectId } = require('mongodb');
const axios = require('axios');
let endpoint = process.env.AZURE_COSMOS_RESOURCEENDPOINT;
let listConnectionStringUrl = process.env.AZURE_COSMOS_LISTCONNECTIONSTRINGURL;
let scope = process.env.AZURE_COSMOS_SCOPE;
// Uncomment the following lines corresponding to the authentication type you want to use.
// For system-assigned identity.
// const credential = new DefaultAzureCredential();
// For user-assigned identity.
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const credential = new DefaultAzureCredential({
// managedIdentityClientId: clientId
// });
// For service principal.
// const tenantId = process.env.AZURE_COSMOS_TENANTID;
// const clientId = process.env.AZURE_COSMOS_CLIENTID;
// const clientSecret = process.env.AZURE_COSMOS_CLIENTSECRET;
// Acquire the access token.
var accessToken = await credential.getToken(scope);
// Get the connection string.
const config = {
method: 'post',
url: listConnectionStringUrl,
headers: {
'Authorization': `Bearer ${accessToken.token}`
}
};
const response = await axios(config);
const keysDict = response.data;
const connectionString = keysDict['connectionStrings'][0]['connectionString'];
const client = new MongoClient(connectionString);
后续步骤
参考下面列出的教程来详细了解服务连接器。