クライアント ライブラリ Azure.Identity を使用して、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
// 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 を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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.credentital.*;
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 according to the authentication type.
// 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接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
# 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接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for MongoDB に接続します。 次のコードを使用する場合は、使用する認証の種類のコード スニペットの部分をコメント解除します。
コードでは、アクセス トークンを取得し、それを使用して@azure/identity接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
// 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);
その他の言語では、MongoDB リソース エンドポイントと、Service Connector が環境変数に設定するその他のプロパティを使用して、Azure Cosmos DB for MongoDB に接続できます。 環境変数の詳細については、「Azure Cosmos DB for MongoDB と Service Connector の統合」を参照してください。
クライアント ライブラリ Azure.Identity を使用して、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
// 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 を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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.credentital.*;
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 according to the authentication type.
// 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接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
# 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接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for MongoDB に接続します。 次のコードを使用する場合は、使用する認証の種類のコード スニペットの部分をコメント解除します。
コードでは、アクセス トークンを取得し、それを使用して@azure/identity接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
// 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);
その他の言語では、MongoDB リソース エンドポイントと、Service Connector が環境変数に設定するその他のプロパティを使用して、Azure Cosmos DB for MongoDB に接続できます。 環境変数の詳細については、「Azure Cosmos DB for MongoDB と Service Connector の統合」を参照してください。
Service Connector によって追加された環境変数から接続文字列を取得し、Azure Cosmos DB for MongoDB に接続します。
using MongoDB.Driver;
var connectionString = Environment.GetEnvironmentVariable("AZURE_COSMOS_CONNECTIONSTRING");
var client = new MongoClient(connectionString);
Service Connector によって追加された環境変数から接続文字列を取得し、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();
}
}
Spring アプリケーションを設定するには 、「Azure Cosmos DB for MongoDB API で Spring Data を使用する」を参照してください。 構成プロパティ spring.data.mongodb.database 。 spring.data.mongodb.uri Spring Apps by Service Connector に設定されます。
依存関係をインストールします。
pip install pymongo
Service Connector によって追加された環境変数から接続文字列を取得し、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
Service Connector によって追加された環境変数から接続文字列を取得し、Azure Cosmos DB for MongoDB に接続します。
その他の言語では、MongoDB リソース エンドポイントと、Service Connector が環境変数に設定するその他のプロパティを使用して、Azure Cosmos DB for MongoDB に接続できます。 環境変数の詳細については、「Azure Cosmos DB for MongoDB と Service Connector の統合」を参照してください。
クライアント ライブラリ Azure.Identity を使用して、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
// 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 を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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.credentital.*;
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 according to the authentication type.
// 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接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
# 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接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for MongoDB に接続します。 次のコードを使用する場合は、使用する認証の種類のコード スニペットの部分をコメント解除します。
コードでは、アクセス トークンを取得し、それを使用して@azure/identity接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、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 according to the authentication type.
// 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);
その他の言語では、MongoDB リソース エンドポイントと、Service Connector が環境変数に設定するその他のプロパティを使用して、Azure Cosmos DB for MongoDB に接続できます。 環境変数の詳細については、「Azure Cosmos DB for MongoDB と Service Connector の統合」を参照してください。