Partilhar via


Integrar o Azure Cosmos DB para Tabela com o Service Connector

Esta página mostra os métodos de autenticação e os clientes suportados e mostra o código de exemplo que pode utilizar para ligar o Azure Cosmos DB for Table a outros serviços na nuvem utilizando o Service Connector. Talvez você ainda consiga se conectar ao Azure Cosmos DB for Table em outras linguagens de programação sem usar o Service Connector. Esta página também mostra nomes e valores de variáveis de ambiente padrão que você obtém quando cria a conexão de serviço.

Serviços de computação suportados

O Service Connector pode ser usado para conectar os seguintes serviços de computação ao Azure Cosmos DB for Table:

  • Serviço de Aplicações do Azure
  • Funções do Azure
  • Azure Container Apps
  • Azure Spring Apps

Tipos de autenticação e tipos de cliente suportados

A tabela abaixo mostra quais combinações de tipos de cliente e métodos de autenticação têm suporte para conectar seu serviço de computação ao Azure Cosmos DB for Table usando o Service Connector. Um "Sim" indica que a combinação é suportada, enquanto um "Não" indica que ela não é suportada.

Tipo de cliente Identidade gerida atribuída pelo sistema Identidade gerida atribuída pelo utilizador Segredo / cadeia de conexão Service principal (Principal de serviço)
.NET Sim Sim Sim Sim
Java Sim Sim Sim Sim
Node.js Sim Sim Sim Sim
Python Sim Sim Sim Sim
Go Sim Sim Sim Sim
None Sim Sim Sim Sim

Esta tabela indica que todas as combinações de tipos de cliente e métodos de autenticação na tabela são suportadas. Todos os tipos de cliente podem usar qualquer um dos métodos de autenticação para se conectar ao Azure Cosmos DB for Table usando o Service Connector.

Nomes de variáveis de ambiente padrão ou propriedades de aplicativo e código de exemplo

Use os detalhes de conexão abaixo para conectar seus serviços de computação ao Azure Cosmos DB for Table. Para cada exemplo abaixo, substitua os textos <account-name>de espaço reservado , , , , <resource-group-name><subscription-ID><table-name><account-key>, , , <client-ID><client-secret>com <tenant-id> suas próprias informações. Para obter mais informações sobre convenções de nomenclatura, consulte o artigo interno do Service Connector.

Identidade gerida atribuída pelo sistema

Nome da variável de ambiente padrão Description Valor de exemplo
AZURE_COSMOS_LISTCONNECTIONSTRINGURL A URL para obter a cadeia de conexão 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 Seu escopo de identidade gerenciado https://management.azure.com/.default
AZURE_COSMOS_RESOURCEENDPOINT Seu ponto de extremidade de recurso https://<table-name>.documents.azure.com:443/

Código de exemplo

Consulte as etapas e o código abaixo para se conectar ao Azure Cosmos DB for Table usando uma identidade gerenciada atribuída ao sistema.

  1. Instale dependências.
    dotnet add package Azure.Data.Tables
    dotnet add package Azure.Identity
    
  2. Obtenha um token de acesso para a identidade gerenciada ou a entidade de serviço usando a biblioteca de cliente Azure.Identity. Use o token de acesso e AZURE_COSMOS_LISTCONNECTIONSTRINGURL para obter a cadeia de conexão. Obtenha as informações de conexão das variáveis de ambiente adicionadas pelo Service Connector e conecte-se ao Azure Cosmos DB for Table. Ao usar o código abaixo, descomente a parte do trecho de código para o tipo de autenticação que você deseja usar.
    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);
    

Identidade gerida atribuída pelo utilizador

Nome da variável de ambiente padrão Description Valor de exemplo
AZURE_COSMOS_LISTCONNECTIONSTRINGURL A URL para obter a cadeia de conexão 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 Seu escopo de identidade gerenciado https://management.azure.com/.default
AZURE_COSMOS_CLIENTID O ID secreto do seu cliente <client-ID>
AZURE_COSMOS_RESOURCEENDPOINT Seu ponto de extremidade de recurso https://<table-name>.documents.azure.com:443/

Código de exemplo

Consulte as etapas e o código abaixo para se conectar ao Azure Cosmos DB for Table usando uma identidade gerenciada atribuída pelo usuário.

  1. Instale dependências.
    dotnet add package Azure.Data.Tables
    dotnet add package Azure.Identity
    
  2. Obtenha um token de acesso para a identidade gerenciada ou a entidade de serviço usando a biblioteca de cliente Azure.Identity. Use o token de acesso e AZURE_COSMOS_LISTCONNECTIONSTRINGURL para obter a cadeia de conexão. Obtenha as informações de conexão das variáveis de ambiente adicionadas pelo Service Connector e conecte-se ao Azure Cosmos DB for Table. Ao usar o código abaixo, descomente a parte do trecho de código para o tipo de autenticação que você deseja usar.
    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);
    

Connection string

Nome da variável de ambiente padrão Description Valor de exemplo
AZURE_COSMOS_CONNECTIONSTRING Cadeia de conexão do Azure Cosmos DB for Table DefaultEndpointsProtocol=https;AccountName=<account-name>;AccountKey=<account-key>;TableEndpoint=https://<table-name>.table.cosmos.azure.com:443/;

Código de exemplo

Consulte as etapas e o código abaixo para se conectar ao Azure Cosmos DB for Table usando uma cadeia de conexão.

  1. Instalar dependência.

    dotnet add package Azure.Data.Tables
    
  2. Obtenha a cadeia de conexão da variável de ambiente adicionada pelo Service Connector.

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

Service principal (Principal de serviço)

Nome da variável de ambiente padrão Description Valor de exemplo
AZURE_COSMOS_LISTCONNECTIONSTRINGURL A URL para obter a cadeia de conexão 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 Seu escopo de identidade gerenciado https://management.azure.com/.default
AZURE_COSMOS_CLIENTID O ID secreto do seu cliente <client-ID>
AZURE_COSMOS_CLIENTSECRET O segredo do seu cliente <client-secret>
AZURE_COSMOS_TENANTID O seu ID de inquilino <tenant-ID>
AZURE_COSMOS_RESOURCEENDPOINT Seu ponto de extremidade de recurso https://<table-name>.documents.azure.com:443/

Código de exemplo

Consulte as etapas e o código abaixo para se conectar ao Azure Cosmos DB for Table usando uma entidade de serviço.

  1. Instale dependências.
    dotnet add package Azure.Data.Tables
    dotnet add package Azure.Identity
    
  2. Obtenha um token de acesso para a identidade gerenciada ou a entidade de serviço usando a biblioteca de cliente Azure.Identity. Use o token de acesso e AZURE_COSMOS_LISTCONNECTIONSTRINGURL para obter a cadeia de conexão. Obtenha as informações de conexão das variáveis de ambiente adicionadas pelo Service Connector e conecte-se ao Azure Cosmos DB for Table. Ao usar o código abaixo, descomente a parte do trecho de código para o tipo de autenticação que você deseja usar.
    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);
    

Próximos passos

Siga os tutoriais listados abaixo para saber mais sobre o Service Connector.