이 페이지에는 지원되는 인증 방법 및 클라이언트가 표시되며, 서비스 커넥터를 사용하여 Azure Cosmos DB for MongoDB를 다른 클라우드 서비스에 연결하는 데 사용할 수 있는 샘플 코드가 표시됩니다. 서비스 커넥터를 사용하지 않고 다른 프로그래밍 언어로 Azure Cosmos DB for MongoDB에 계속 연결할 수 있습니다. 이 페이지에서는 서비스 연결을 만들 때 가져오는 기본 환경 변수 이름과 값(또는 Spring Boot 구성)도 보여 줍니다.
지원되는 컴퓨팅 서비스
서비스 커넥터를 사용하여 다음 컴퓨팅 서비스를 Azure Cosmos DB for MongoDB에 연결할 수 있습니다.
- Azure App Service
- Azure Container Apps
- Azure Functions
- AKS(Azure Kubernetes Service)
- Azure Spring Apps
지원되는 인증 유형 및 클라이언트 유형
아래 표에서는 서비스 커넥터를 사용하여 컴퓨팅 서비스를 Azure Cosmos DB for MongoDB에 연결하는 데 지원되는 클라이언트 유형 및 인증 방법의 조합을 보여 줍니다. 해당 조합이 지원되면 “예”, 지원되지 않으면 “아니요”입니다.
클라이언트 유형 |
시스템 할당 관리 ID |
사용자 할당 관리 ID |
비밀/연결 문자열 |
서비스 주체 |
.NET |
예 |
예 |
예 |
예 |
Java |
예 |
예 |
예 |
예 |
Java - Spring Boot |
아니요 |
아니요 |
예 |
아니요 |
Node.js |
예 |
예 |
예 |
예 |
Python |
예 |
예 |
예 |
예 |
Go |
예 |
예 |
예 |
예 |
None |
예 |
예 |
예 |
예 |
이 표는 비밀/연결 문자열 메서드만 지원하는 Java - Spring Boot 클라이언트 유형을 제외하고 표에 클라이언트 유형과 인증 방법의 모든 조합이 지원됨을 나타냅니다. 다른 모든 클라이언트 유형은 인증 방법을 사용하여 서비스 커넥터를 통해 Azure Cosmos DB for MongoDB에 연결할 수 있습니다.
비고
Cosmos DB는 기본적으로 관리 ID를 통한 인증을 지원하지 않습니다. 따라서 서비스 커넥터는 관리 ID를 사용하여 연결 문자열을 검색하고, 이후 해당 연결 문자열을 사용하여 연결이 설정됩니다.
기본 환경 변수 이름 또는 애플리케이션 속성과 샘플 코드
아래의 연결 세부 정보를 사용하여 컴퓨팅 서비스를 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>
를 고유의 정보로 바꿉니다. 명명 규칙에 대한 자세한 내용은 서비스 커넥터 내부 문서를 참조하세요.
시스템 할당 관리 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 |
관리 ID 범위 |
https://management.azure.com/.default |
AZURE_COSMOS_RESOURCEENDPOINT |
리소스 엔드포인트 |
https://<Azure-Cosmos-DB-API-for-MongoDB-account>.documents.azure.com:443/ |
예제 코드
시스템이 할당한 관리 ID를 사용하여 Azure Cosmos DB for MongoDB에 연결하려면 아래 단계 및 코드를 참조하세요.
Cosmos DB는 기본적으로 관리 ID를 통한 인증을 지원하지 않으므로 다음 코드 샘플에서는 관리 ID를 사용하여 연결 문자열을 검색한 다음 해당 연결 문자열을 사용하여 연결을 설정합니다.
종속성 설치
dotnet add package MongoDb.Driver
dotnet add package Azure.Identity
클라이언트 라이브러리 Azure.Identity를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 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
를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 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)
종속성 설치
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);
사용자 할당 관리 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 |
관리 ID 범위 |
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/ |
예제 코드
사용자가 할당한 관리 ID를 사용하여 Azure Cosmos DB for MongoDB에 연결하려면 아래 단계 및 코드를 참조하세요.
Cosmos DB는 기본적으로 관리 ID를 통한 인증을 지원하지 않으므로 다음 코드 샘플에서는 관리 ID를 사용하여 연결 문자열을 검색한 다음 해당 연결 문자열을 사용하여 연결을 설정합니다.
종속성 설치
dotnet add package MongoDb.Driver
dotnet add package Azure.Identity
클라이언트 라이브러리 Azure.Identity를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 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
를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 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)
종속성 설치
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에서는 사용 가능한 가장 안전한 인증 흐름을 사용하는 것이 좋습니다. 이 절차에 설명된 인증 흐름은 애플리케이션에 대한 매우 높은 수준의 신뢰를 요구하며, 다른 흐름에는 존재하지 않는 위험을 수반합니다. 관리 ID와 같이 다른 보안 흐름이 실행 가능하지 않은 경우에만 이 흐름을 사용해야 합니다.
Spring Boot 클라이언트 유형
기본 환경 변수 이름 |
설명 |
예제 값 |
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 |
관리 ID 범위 |
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를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 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
를 사용하여 관리 ID 또는 서비스 주체에 대한 액세스 토큰을 가져옵니다. 액세스 토큰 및 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)
종속성 설치
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);
다음 단계
서비스 커넥터에 대해 자세히 알아보려면 아래 나열된 자습서를 따르세요.