此頁面顯示支援的驗證方法和用戶端,並顯示可讓您使用服務連接器將 Azure Cosmos DB for MongoDB 連線至其他雲端服務的範例程式碼。 在未使用服務連接器的情況下,您仍可透過其他程式設計語言連線至 Azure Cosmos DB for MongoDB。 此頁面也顯示您在建立服務連線時取得的預設環境變數名稱和值 (或 Spring Boot 設定)。
支援的計算服務
服務連接器可用來將下列計算服務連線至 Azure Cosmos DB for MongoDB:
Azure App Service
Azure 容器應用程式
Azure Functions
Azure Kubernetes Service (AKS)
Azure Spring Apps
支援的驗證類型和用戶端類型
下表說明使用服務連接器將計算服務連線至 Azure Cosmos DB for MongoDB 時,支援哪些用戶端類型和驗證方法的組合。 「是」表示支援的組合,而「否」則表示不支援。
用戶端類型
系統指派的受控識別
使用者指派的受控識別
祕密 / 連接字串
服務主體
.NET
Yes
.是
.是
Yes
Java
Yes
.是
.是
Yes
Java - Spring Boot
No
無
.是
No
Node.js
Yes
.是
.是
Yes
Python
Yes
.是
.是
Yes
Go
Yes
.是
.是
Yes
無
Yes
.是
.是
Yes
此表指出表中所有用戶端類型和驗證方法的組合均受支援,但 Java - Spring Boot 用戶端類型 (其僅支援秘密/連接字串方法) 除外。 所有其他用戶端類型都可以使用任何驗證方法,使用服務連接器連線至 Azure Cosmos DB for MongoDB。
使用用戶端程式庫 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;
var endpoint = 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(listConnectionStringUrl);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
string connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
使用 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);
Spring Boot 不支援驗證類型。
安裝相依性。
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)
使用用戶端程式庫 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;
var endpoint = 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(listConnectionStringUrl);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
string connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
使用 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);
Spring Boot 不支援驗證類型。
安裝相依性。
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)
從服務連接器新增的環境變數取得連接字串,並連線至 Azure Cosmos DB for MongoDB。
using MongoDB.Driver;
var connectionString = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONNECTIONSTRING");
var client = new MongoClient(connectionString);
使用用戶端程式庫 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;
var endpoint = 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(listConnectionStringUrl);
var responseBody = await response.Content.ReadAsStringAsync();
var connectionStrings = JsonSerializer.Deserialize<Dictionary<string, List<Dictionary<string, string>>>>(responseBody);
string connectionString = connectionStrings["connectionStrings"][0]["connectionString"];
// Connect to Azure Cosmos DB for MongoDB
var client = new MongoClient(connectionString);
使用 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);
Spring Boot 不支援驗證類型。
安裝相依性。
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)