次の方法で共有


Azure Cosmos DB for Table と Service Connector を統合する

このページでは、サポートされている認証方法とクライアントを示し、Service Connector を使用して Azure Cosmos DB for Table を他のクラウド サービスに接続するために使用できるサンプル コードを示します。 Service Connector を使用しなくても、他のプログラミング言語で Azure Cosmos DB for Table に接続できる場合があります。 このページには、サービス接続を作成するときに取得する既定の環境変数の名前と値も示されています。

サポートされているコンピューティング サービス

Service Connector を使用して、次のコンピューティング サービスを Azure Cosmos DB for Table に接続できます。

  • Azure App Service
  • Azure Functions
  • Azure Container Apps
  • Azure Spring Apps

サポートされている認証の種類とクライアントの種類

次の表は、Service Connector を使用してコンピューティング サービスを Azure Cosmos DB for Table に接続するためにサポートされているクライアントの種類と認証方法の組み合わせを示しています。 "はい" は組み合わせがサポートされていることを示し、"いいえ" はサポートされていないことを示します。

クライアント タイプ システム割り当てマネージド ID ユーザー割り当てマネージド ID シークレット/接続文字列 サービス プリンシパル
.NET はい イエス イエス はい
Java はい イエス イエス はい
Node.js はい イエス イエス はい
Python はい イエス イエス はい
Go はい イエス イエス はい
なし 有効 イエス イエス はい

この表は、表内のクライアント・タイプと認証方法のすべての組み合わせがサポートされていることを示しています。 すべてのクライアントの種類では、任意の認証方法を使用して、Service Connector を使用して Azure Cosmos DB for Table に接続できます。

既定の環境変数名またはアプリケーション プロパティとサンプル コード

次の接続の詳細を使用して、コンピューティング サービスを Azure Cosmos DB for Table に接続します。 以下の各例では、プレースホルダーのテキスト <account-name><table-name><account-key><resource-group-name><subscription-ID><client-ID><client-secret><tenant-id> を実際の情報に置き換えます。 名前付け規則の詳細については、Service Connector の内部の記事を参照してください。

システム割り当てマネージド ID

既定の環境変数名 説明 例値
AZURE_COSMOS_LISTCONNECTIONSTRINGURL 接続文字列を取得するための URL https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<table-name>/listConnectionStrings?api-version=2021-04-15
AZURE_COSMOS_SCOPE マネージド ID の範囲 https://management.azure.com/.default
AZURE_COSMOS_RESOURCEENDPOINT リソース エンドポイント https://<table-name>.documents.azure.com:443/

サンプル コード

システム割り当てマネージド ID を使用して Azure Cosmos DB for Table に接続するには、以下の手順とコードを参照してください。

  1. 依存関係をインストールします。
    dotnet add package Azure.Data.Tables
    dotnet add package Azure.Identity
    
  2. クライアント ライブラリ Azure.Identity を使用して、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
    using System;
    using System.Security.Authentication;
    using System.Net.Security;
    using System.Net.Http;
    using System.Security.Authentication;
    using System.Threading.Tasks;
    using Azure.Data.Tables;
    using Azure.Identity;
    
    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 = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, string>>>(responseBody);
    var connectionString = connectionStrings["connectionStrings"].Find(connStr => connStr["description"] == "Primary Table Connection String")["connectionString"];
    
    // Connect to Azure Cosmos DB for Table
    TableServiceClient tableServiceClient = new TableServiceClient(connectionString);
    

ユーザー割り当てマネージド ID

既定の環境変数名 説明 例値
AZURE_COSMOS_LISTCONNECTIONSTRINGURL 接続文字列を取得するための URL https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<table-name>/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://<table-name>.documents.azure.com:443/

サンプル コード

ユーザー割り当てマネージド ID を使用して Azure Cosmos DB for Table に接続するには、以下の手順とコードを参照してください。

  1. 依存関係をインストールします。
    dotnet add package Azure.Data.Tables
    dotnet add package Azure.Identity
    
  2. クライアント ライブラリ Azure.Identity を使用して、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
    using System;
    using System.Security.Authentication;
    using System.Net.Security;
    using System.Net.Http;
    using System.Security.Authentication;
    using System.Threading.Tasks;
    using Azure.Data.Tables;
    using Azure.Identity;
    
    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 = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, string>>>(responseBody);
    var connectionString = connectionStrings["connectionStrings"].Find(connStr => connStr["description"] == "Primary Table Connection String")["connectionString"];
    
    // Connect to Azure Cosmos DB for Table
    TableServiceClient tableServiceClient = new TableServiceClient(connectionString);
    

接続文字列

既定の環境変数名 説明 例値
AZURE_COSMOS_CONNECTIONSTRING Azure Cosmos DB for Table の接続文字列 DefaultEndpointsProtocol=https;AccountName=<account-name>;AccountKey=<account-key>;TableEndpoint=https://<table-name>.table.cosmos.azure.com:443/;

サンプル コード

接続文字列を使用して Azure Cosmos DB for Table に接続するには、以下の手順とコードを参照してください。

  1. 依存関係をインストールします。

    dotnet add package Azure.Data.Tables
    
  2. Service Connector によって追加された環境変数から接続文字列を取得します。

    using Azure.Data.Tables;
    using System; 
    
    TableServiceClient tableServiceClient = new TableServiceClient(Environment.GetEnvironmentVariable("AZURE_COSMOS_CONNECTIONSTRING"));
    

サービス プリンシパル

既定の環境変数名 説明 例値
AZURE_COSMOS_LISTCONNECTIONSTRINGURL 接続文字列を取得するための URL https://management.azure.com/subscriptions/<subscription-ID>/resourceGroups/<resource-group-name>/providers/Microsoft.DocumentDB/databaseAccounts/<table-name>/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://<table-name>.documents.azure.com:443/

サンプル コード

サービス プリンシパルを使用して Azure Cosmos DB for Table に接続するには、以下の手順とコードを参照してください。

  1. 依存関係をインストールします。
    dotnet add package Azure.Data.Tables
    dotnet add package Azure.Identity
    
  2. クライアント ライブラリ Azure.Identity を使用して、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンを使用して、AZURE_COSMOS_LISTCONNECTIONSTRINGURL接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
    using System;
    using System.Security.Authentication;
    using System.Net.Security;
    using System.Net.Http;
    using System.Security.Authentication;
    using System.Threading.Tasks;
    using Azure.Data.Tables;
    using Azure.Identity;
    
    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 = JsonConvert.DeserializeObject<Dictionary<string, List<Dictionary<string, string>>>(responseBody);
    var connectionString = connectionStrings["connectionStrings"].Find(connStr => connStr["description"] == "Primary Table Connection String")["connectionString"];
    
    // Connect to Azure Cosmos DB for Table
    TableServiceClient tableServiceClient = new TableServiceClient(connectionString);
    

次のステップ

Service Connector の詳細については、以下のチュートリアルに従ってください。