このページでは、サポートされている認証方法とクライアントを示し、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 Container Apps
- Azure Functions
- Azure Kubernetes Service (AKS)
- Azure Spring Apps
サポートされている認証の種類とクライアントの種類
次の表は、Service Connector を使った Azure Cosmos DB for Table へのコンピューティング サービスの接続でサポートされているクライアントの種類と認証方法の組み合わせを示したものです。 "はい" はその組み合わせがサポートされていることを示し、"いいえ" はサポートされていないことを示します。
クライアント タイプ |
システム割り当てマネージド ID |
ユーザー割り当てマネージド ID |
シークレット/接続文字列 |
サービス プリンシパル |
.NET |
はい |
イエス |
イエス |
はい |
Java |
はい |
イエス |
イエス |
はい |
Node.js |
はい |
イエス |
イエス |
はい |
Python |
はい |
イエス |
イエス |
はい |
Go |
はい |
イエス |
イエス |
はい |
なし |
有効 |
イエス |
イエス |
はい |
この表は、表内のクライアントの種類と認証方法のすべての組み合わせがサポートされていることを示しています。 すべてのクライアントの種類では、サービス コネクタを使って 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 に接続するには、次の手順とコードを参照してください。
- 依存関係をインストールします。
dotnet add package Azure.Data.Tables
dotnet add package Azure.Identity
- クライアント ライブラリ 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 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 = 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);
- pom.xml ファイルに次の依存関係を追加します:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-data-tables</artifactId>
<version>12.2.1</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンと AZURE_COSMOS_LISTCONNECTIONSTRINGURL
を使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import com.azure.data.tables.TableClient;
import com.azure.data.tables.TableClientBuilder;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
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;
for (Map<String, String> connStr : connectionStrings){
if (connStr.get("description") == "Primary Table Connection String"){
connectionString = connStr.get("connectionString");
break;
}
}
// Connect to Azure Cosmos DB for Table
TableClient tableClient = new TableClientBuilder()
.connectionString(connectionString)
.buildClient();
- 依存関係をインストールします。
pip install azure-data-tables
pip install azure-identity
azure-identity
を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンと AZURE_COSMOS_LISTCONNECTIONSTRINGURL
を使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import os
from azure.data.tables import TableServiceClient
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 = x["connectionString"] for x in keys_dict["connectionStrings"] if x["description"] == "Primary Table Connection String"
# Connect to Azure Cosmos DB for Table
table_service = TableServiceClient.from_connection_string(conn_str)
- 依存関係をインストールします。
go get github.com/Azure/azure-sdk-for-go/sdk/data/aztables
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
- コードでは、
@azidentity
を使用してアクセス トークンを取得し、それを使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"github.com/Azure/azure-sdk-for-go/sdk/data/aztables"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
func main() {
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)
connStr := ""
for i := range result["connectionStrings"]{
if result["connectionStrings"][i]["description"] == "Primary Table Connection String" {
connStr, err := result["connectionStrings"][i]["connectionString"]
break
}
}
serviceClient, err := aztables.NewServiceClientFromConnectionString(connStr, nil)
if err != nil {
panic(err)
}
}
- 依存関係のインストール
npm install @azure/data-tables
npm install --save @azure/identity
- コードでは、
@azure/identity
を使用してアクセス トークンを取得し、それを使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { TableClient } = require("@azure/data-tables");
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"].find(connStr => connStr["description"] == "Primary Table Connection String")["connectionString"];
// Connect to Azure Cosmos DB for Table
const serviceClient = TableClient.fromConnectionString(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 に接続するには、次の手順とコードを参照してください。
- 依存関係をインストールします。
dotnet add package Azure.Data.Tables
dotnet add package Azure.Identity
- クライアント ライブラリ 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 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 = 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);
- pom.xml ファイルに次の依存関係を追加します:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-data-tables</artifactId>
<version>12.2.1</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンと AZURE_COSMOS_LISTCONNECTIONSTRINGURL
を使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import com.azure.data.tables.TableClient;
import com.azure.data.tables.TableClientBuilder;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
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;
for (Map<String, String> connStr : connectionStrings){
if (connStr.get("description") == "Primary Table Connection String"){
connectionString = connStr.get("connectionString");
break;
}
}
// Connect to Azure Cosmos DB for Table
TableClient tableClient = new TableClientBuilder()
.connectionString(connectionString)
.buildClient();
- 依存関係をインストールします。
pip install azure-data-tables
pip install azure-identity
azure-identity
を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンと AZURE_COSMOS_LISTCONNECTIONSTRINGURL
を使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import os
from azure.data.tables import TableServiceClient
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 = x["connectionString"] for x in keys_dict["connectionStrings"] if x["description"] == "Primary Table Connection String"
# Connect to Azure Cosmos DB for Table
table_service = TableServiceClient.from_connection_string(conn_str)
- 依存関係をインストールします。
go get github.com/Azure/azure-sdk-for-go/sdk/data/aztables
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
- コードでは、
@azidentity
を使用してアクセス トークンを取得し、それを使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"github.com/Azure/azure-sdk-for-go/sdk/data/aztables"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
func main() {
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)
connStr := ""
for i := range result["connectionStrings"]{
if result["connectionStrings"][i]["description"] == "Primary Table Connection String" {
connStr, err := result["connectionStrings"][i]["connectionString"]
break
}
}
serviceClient, err := aztables.NewServiceClientFromConnectionString(connStr, nil)
if err != nil {
panic(err)
}
}
- 依存関係のインストール
npm install @azure/data-tables
npm install --save @azure/identity
- コードでは、
@azure/identity
を使用してアクセス トークンを取得し、それを使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { TableClient } = require("@azure/data-tables");
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"].find(connStr => connStr["description"] == "Primary Table Connection String")["connectionString"];
// Connect to Azure Cosmos DB for Table
const serviceClient = TableClient.fromConnectionString(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/; |
警告
Microsoft では、使用可能な最も安全な認証フローを使用することをお勧めします。 この手順で説明されている認証フローでは、アプリケーションで非常に高い信頼度が要求されるため、他のフローには存在しないリスクが伴います。 このフローは、マネージド ID など、より安全なフローが実行可能ではない場合にのみ使用してください。
サンプル コード
接続文字列を使用して Azure Cosmos DB for Table に接続するには、次の手順とコードを参照してください。
依存関係をインストールします。
dotnet add package Azure.Data.Tables
Service Connector によって追加された環境変数から接続文字列を取得します。
using Azure.Data.Tables;
using System;
TableServiceClient tableServiceClient = new TableServiceClient(Environment.GetEnvironmentVariable("AZURE_COSMOS_CONNECTIONSTRING"));
pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-data-tables</artifactId>
<version>12.2.1</version>
</dependency>
Service Connector によって追加された環境変数から接続文字列を取得します。
import com.azure.data.tables.TableClient;
import com.azure.data.tables.TableClientBuilder;
String connectionStr = System.getenv("AZURE_COSMOS_CONNECTIONSTRING");
TableClient tableClient = new TableClientBuilder()
.connectionString(connectionStr)
.buildClient();
依存関係をインストールします。
pip install azure-data-tables
Service Connector によって追加された環境変数から接続文字列を取得します。
import os
from azure.data.tables import TableServiceClient
conn_str = os.environ["AZURE_COSMOS_CONNECTIONSTRING"]
table_service = TableServiceClient.from_connection_string(conn_str)
- 依存関係をインストールします。
go get github.com/Azure/azure-sdk-for-go/sdk/data/aztables
- Service Connector によって追加された環境変数から接続文字列を取得します。
import (
"github.com/Azure/azure-sdk-for-go/sdk/data/aztables"
)
func main() {
connStr := os.Getenv("AZURE_COSMOS_CONNECTIONSTRING")
serviceClient, err := aztables.NewServiceClientFromConnectionString(connStr, nil)
if err != nil {
panic(err)
}
}
依存関係をインストールします。
npm install @azure/data-tables
Service Connector によって追加された環境変数から接続文字列を取得します。
const { TableClient } = require("@azure/data-tables");
const serviceClient = TableClient.fromConnectionString(process.env.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 に接続するには、次の手順とコードを参照してください。
- 依存関係をインストールします。
dotnet add package Azure.Data.Tables
dotnet add package Azure.Identity
- クライアント ライブラリ 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 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 = 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);
- pom.xml ファイルに次の依存関係を追加します:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-data-tables</artifactId>
<version>12.2.1</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.1.5</version>
</dependency>
azure-identity
を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンと AZURE_COSMOS_LISTCONNECTIONSTRINGURL
を使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import com.azure.data.tables.TableClient;
import com.azure.data.tables.TableClientBuilder;
import javax.net.ssl.*;
import java.net.InetSocketAddress;
import com.azure.identity.*;
import com.azure.core.credential.*;
import java.net.http.*;
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;
for (Map<String, String> connStr : connectionStrings){
if (connStr.get("description") == "Primary Table Connection String"){
connectionString = connStr.get("connectionString");
break;
}
}
// Connect to Azure Cosmos DB for Table
TableClient tableClient = new TableClientBuilder()
.connectionString(connectionString)
.buildClient();
- 依存関係をインストールします。
pip install azure-data-tables
pip install azure-identity
azure-identity
を使って、マネージド ID またはサービス プリンシパルのアクセス トークンを取得します。 アクセス トークンと AZURE_COSMOS_LISTCONNECTIONSTRINGURL
を使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import os
from azure.data.tables import TableServiceClient
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 = x["connectionString"] for x in keys_dict["connectionStrings"] if x["description"] == "Primary Table Connection String"
# Connect to Azure Cosmos DB for Table
table_service = TableServiceClient.from_connection_string(conn_str)
- 依存関係をインストールします。
go get github.com/Azure/azure-sdk-for-go/sdk/data/aztables
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
- コードでは、
@azidentity
を使用してアクセス トークンを取得し、それを使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import (
"fmt"
"os"
"context"
"log"
"io/ioutil"
"encoding/json"
"github.com/Azure/azure-sdk-for-go/sdk/data/aztables"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)
func main() {
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)
connStr := ""
for i := range result["connectionStrings"]{
if result["connectionStrings"][i]["description"] == "Primary Table Connection String" {
connStr, err := result["connectionStrings"][i]["connectionString"]
break
}
}
serviceClient, err := aztables.NewServiceClientFromConnectionString(connStr, nil)
if err != nil {
panic(err)
}
}
- 依存関係のインストール
npm install @azure/data-tables
npm install --save @azure/identity
- コードでは、
@azure/identity
を使用してアクセス トークンを取得し、それを使用して接続文字列を取得します。 Service Connector によって追加された環境変数から接続情報を取得し、Azure Cosmos DB for Table に接続します。 次のコードを使用する場合は、使用する認証型のコード スニペットの一部をコメント解除します。
import { DefaultAzureCredential,ClientSecretCredential } from "@azure/identity";
const { TableClient } = require("@azure/data-tables");
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"].find(connStr => connStr["description"] == "Primary Table Connection String")["connectionString"];
// Connect to Azure Cosmos DB for Table
const serviceClient = TableClient.fromConnectionString(connectionString);
次のステップ
Service Connector の詳細については、以下のチュートリアルに従ってください。