使用服務連接器整合 Azure Cosmos DB for Table
本文內容
此頁面顯示支援的驗證方法和用戶端,並顯示可讓您使用服務連接器將 Azure Cosmos DB for Table 連線至其他雲端服務的範例程式碼。 在未使用服務連接器的情況下,您仍可透過其他程式設計語言連線至 Azure Cosmos DB for Table。 此頁面也顯示您在建立服務連線時取得的預設環境變數名稱和值。
支援的計算服務
服務連接器可用來將下列計算服務連線至 Azure Cosmos DB for Table:
Azure App Service
Azure 容器應用程式
Azure Functions
Azure Kubernetes Service (AKS)
Azure Spring Apps
支援的驗證類型和用戶端類型
下表說明使用服務連接器將計算服務連線至 Azure Cosmos DB for Table 時,支援哪些用戶端類型和驗證方法的組合。 「是」表示支援的組合,而「否」則表示不支援。
用戶端類型
系統指派的受控識別
使用者指派的受控識別
祕密 / 連接字串
服務主體
.NET
Yes
.是
.是
Yes
Java
Yes
.是
.是
Yes
Node.js
Yes
.是
.是
Yes
Python
Yes
.是
.是
Yes
Go
Yes
.是
.是
Yes
無
Yes
.是
.是
Yes
下表指出支源表格中所有用戶端類型和驗證方法組合。 所有用戶端類型都可以使用任何驗證方法,使用服務連接器連線到 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>
取代為您自己的資訊。 如需命名慣例的詳細資訊,請參閱服務連接器內部 一文。
系統指派的受控識別
預設環境變數名稱
描述
範例值
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
您的受控識別範圍
https://management.azure.com/.default
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 取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得存取權杖,然後將其用來取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得存取權杖,然後將其用來取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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_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
您的受控識別範圍
https://management.azure.com/.default
AZURE_COSMOS_CLIENTID
您的用戶端密碼識別碼
<client-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 取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得存取權杖,然後將其用來取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得存取權杖,然後將其用來取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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);
Connection string
預設環境變數名稱
描述
範例值
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 建議您使用最安全的可用驗證流程。 這個程序描述的驗證流程需要在應用程式中具備極高的信任度,且伴隨著其他流程並未面臨的風險。 請僅在其他較安全的流程 (例如受控身分識別) 皆不具可行性的情況下,才使用這個流程。
範例指令碼
請參閱下列步驟和程式碼,使用連接字串連線至 Azure Cosmos DB for Table。
安裝相依性。
dotnet add package Azure.Data.Tables
從服務連接器新增的環境變數取得連接字串。
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>
從服務連接器新增的環境變數取得連接字串。
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
從服務連接器新增的環境變數取得連接字串。
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
從服務連接器新增的環境變數取得連接字串。
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
從服務連接器新增的環境變數取得連接字串。
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
您的受控識別範圍
https://management.azure.com/.default
AZURE_COSMOS_CLIENTID
您的用戶端密碼識別碼
<client-ID>
AZURE_COSMOS_CLIENTSECRET
您的用戶端密碼
<client-secret>
AZURE_COSMOS_TENANTID
您的租用戶識別碼
<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 取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得受控識別或服務主體的存取權杖。 使用存取權杖和 AZURE_COSMOS_LISTCONNECTIONSTRINGURL
取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得存取權杖,然後將其用來取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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
取得存取權杖,然後將其用來取得連接字串。 從服務連接器新增的環境變數取得連線資訊,並連線至 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);
下一步
請遵循下方列出的教學課程以深入了解服務連接器。