使用csharp代码在cosmosdb中创建项目时验证失败

问题描述 投票:0回答:2

我正在按照本教程开始

cosmos db
- https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/quickstart-dotnet?tabs=azure-portal%2Cwindows%2Cpasswordless %2Csign-in-azure-cli#create-account

教程中

cosmos
URI
PRIMARY KEY
在环境变量中导出,在
.cs
代码中使用。但是,仅使用
uri
。他们的钥匙没有被使用。我认为这会导致我的程序在创建项目时无法通过身份验证。

.cs 
代码是

// See https://aka.ms/new-console-template for more information
using Microsoft.Azure.Cosmos;
using Azure.Identity;

// New instance of CosmosClient class
using CosmosClient client = new(
    accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT"),
    tokenCredential: new DefaultAzureCredential()
);




// Database reference with creation if it does not already exist
Database database = client.GetDatabase(id: "cosmicworks");

Console.WriteLine("Hello, World!");

Console.WriteLine($"New database:\t{database.Id}");


// Container reference with creation if it does not alredy exist
Container container = database.GetContainer(id: "products");

Console.WriteLine($"New container:\t{container.Id}");

//THE PROGRAM FAILS SOMEWHERE AFTER THE ABOVE PRINT

// Create new object and upsert (create or replace) to container
Product newItem = new(
    id: "70b63682-b93a-4c77-aad2-65501347265f",
    categoryId: "61dba35b-4f02-45c5-b648-c6badc0cbd79",
    categoryName: "gear-surf-surfboards",
    name: "Yamba Surfboard",
    quantity: 12,
    sale: false
);

Product createdItem = await container.CreateItemAsync<Product>(
    item: newItem//,
    //partitionKey: new PartitionKey("61dba35b-4f02-45c5-b648-c6badc0cbd79")
);

Console.WriteLine($"Created item:\t{createdItem.id}\t[{createdItem.categoryName}]");

// Point read item from container using the id and partitionKey
Product readItem = await container.ReadItemAsync<Product>(
    id: "70b63682-b93a-4c77-aad2-65501347265f",
    partitionKey: new PartitionKey("61dba35b-4f02-45c5-b648-c6badc0cbd79")
);

// Create query using a SQL string and parameters
var query = new QueryDefinition(
    query: "SELECT * FROM products p WHERE p.categoryId = @categoryId"
)
    .WithParameter("@categoryId", "61dba35b-4f02-45c5-b648-c6badc0cbd79");

using FeedIterator<Product> feed = container.GetItemQueryIterator<Product>(
    queryDefinition: query
);

while (feed.HasMoreResults)
{
    FeedResponse<Product> response = await feed.ReadNextAsync();
    foreach (Product item in response)
    {
        Console.WriteLine($"Found item:\t{item.name}");
    }
}


// C# record representing an item in the container
public record Product(
    string id,
    string categoryId,
    string categoryName,
    string name,
    int quantity,
    bool sale
);

输出为

PS /home/manu> dotnet run                         
Hello, World!
New database:   cosmicworks
New container:  products
Unhandled exception. Azure.Identity.AuthenticationFailedException: ManagedIdentityCredential authentication failed: Service request failed.
Status: 400 (Bad Request)

Content:


Headers:
X-Powered-By: REDACTED
ETag: W/"43d-rxaaxO4nRZ43QXDzZ9Qicz6SZeY"
Date: Tue, 28 Feb 2023 06:24:19 GMT
Connection: keep-alive
Keep-Alive: REDACTED
Content-Type: application/json; charset=utf-8
Content-Length: 1085

See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot
 ---> Azure.RequestFailedException: Service request failed.
Status: 400 (Bad Request)

Content:


Headers:
X-Powered-By: REDACTED
ETag: W/"43d-rxaaxO4nRZ43QXDzZ9Qicz6SZeY"
Date: Tue, 28 Feb 2023 06:24:19 GMT
Connection: keep-alive
Keep-Alive: REDACTED
Content-Type: application/json; charset=utf-8
Content-Length: 1085

   at Azure.Identity.ManagedIdentitySource.HandleResponseAsync(Boolean async, TokenRequestContext context, Response response, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentitySource.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentityClient.AuthenticateCoreAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentityClient.AppTokenProviderImpl(AppTokenProviderParameters parameters)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.SendTokenRequestToProviderAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.FetchNewAccessTokenAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters, CancellationToken cancellationToken)
   at Azure.Identity.AbstractAcquireTokenParameterBuilderExtensions.ExecuteAsync[T](AbstractAcquireTokenParameterBuilder`1 builder, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientCoreAsync(String[] scopes, String tenantId, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientAsync(String[] scopes, String tenantId, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Microsoft.Azure.Cosmos.TokenCredentialCache.RefreshCachedTokenWithRetryHelperAsync(ITrace trace)
   at Microsoft.Azure.Cosmos.TokenCredentialCache.RefreshCachedTokenWithRetryHelperAsync(ITrace trace)
   at Microsoft.Azure.Cosmos.TokenCredentialCache.GetNewTokenAsync(ITrace trace)
   at Microsoft.Azure.Cosmos.TokenCredentialCache.GetTokenAsync(ITrace trace)
   at Microsoft.Azure.Cosmos.AuthorizationTokenProviderTokenCredential.AddAuthorizationHeaderAsync(INameValueCollection headersCollection, Uri requestAddress, String verb, AuthorizationTokenType tokenType)
   at Microsoft.Azure.Cosmos.GatewayAccountReader.GetDatabaseAccountAsync(Uri serviceEndpoint)
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetAndUpdateAccountPropertiesAsync(Uri endpoint)
   at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetAccountPropertiesAsync()
   at Microsoft.Azure.Cosmos.GatewayAccountReader.InitializeReaderAsync()
   at Microsoft.Azure.Cosmos.CosmosAccountServiceConfiguration.InitializeAsync()
   at Microsoft.Azure.Cosmos.DocumentClient.InitializeGatewayConfigurationReaderAsync()
   at Microsoft.Azure.Cosmos.DocumentClient.GetInitializationTaskAsync(IStoreClientFactory storeClientFactory)
   at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync[TParam,TPolicy](Func`1 callbackMethod, Func`3 callbackMethodWithParam, Func`2 callbackMethodWithPolicy, TParam param, IRetryPolicy retryPolicy, IRetryPolicy`1 retryPolicyWithArg, Func`1 inBackoffAlternateCallbackMethod, Func`2 inBackoffAlternateCallbackMethodWithPolicy, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback)
   at Microsoft.Azure.Documents.ShouldRetryResult.ThrowIfDoneTrying(ExceptionDispatchInfo capturedException)
   at Microsoft.Azure.Documents.BackoffRetryUtility`1.ExecuteRetryAsync[TParam,TPolicy](Func`1 callbackMethod, Func`3 callbackMethodWithParam, Func`2 callbackMethodWithPolicy, TParam param, IRetryPolicy retryPolicy, IRetryPolicy`1 retryPolicyWithArg, Func`1 inBackoffAlternateCallbackMethod, Func`2 inBackoffAlternateCallbackMethodWithPolicy, TimeSpan minBackoffForInBackoffCallback, CancellationToken cancellationToken, Action`1 preRetryCallback)
   at Microsoft.Azure.Cosmos.AsyncCacheNonBlocking`2.GetAsync(TKey key, Func`2 singleValueInitFunc, Func`2 forceRefresh)
   at Microsoft.Azure.Cosmos.DocumentClient.EnsureValidClientAsync(ITrace trace)
   at Microsoft.Azure.Cosmos.DocumentClient.GetCollectionCacheAsync(ITrace trace)
   at Microsoft.Azure.Cosmos.ContainerCore.GetCachedContainerPropertiesAsync(Boolean forceRefresh, ITrace trace, CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.ContainerCore.GetPartitionKeyDefinitionAsync(CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.ContainerCore.ExtractPartitionKeyAndProcessItemStreamAsync[T](Nullable`1 partitionKey, String itemId, T item, OperationType operationType, ItemRequestOptions requestOptions, ITrace trace, CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.ContainerCore.CreateItemAsync[T](T item, ITrace trace, Nullable`1 partitionKey, ItemRequestOptions requestOptions, CancellationToken cancellationToken)
   at Microsoft.Azure.Cosmos.ClientContextCore.RunWithDiagnosticsHelperAsync[TResult](String containerName, String databaseName, OperationType operationType, ITrace trace, Func`2 task, Func`2 openTelemetry, String operationName, RequestOptions requestOptions)
   at Microsoft.Azure.Cosmos.ClientContextCore.OperationHelperWithRootTraceAsync[TResult](String operationName, String containerName, String databaseName, OperationType operationType, RequestOptions requestOptions, Func`2 task, Func`2 openTelemetry, TraceComponent traceComponent, TraceLevel traceLevel)
   at Program.<Main>$(String[] args) in /home/manu/Program.cs:line 38
   at Program.<Main>(String[] args)
PS /home/manu>                       

我有两个问题

  1. 如果我想在代码中使用

    PRIMARY KEY
    作为环境变量,我应该在
    .cs
    代码中的什么地方使用它。

  2. 如果我想使用

    key-vault
    而不使用环境变量,我如何将
    secrets
    for
    uri
    key
    指向
    .cs
    程序?我检查了本教程,但它没有告诉我如何将
    keyvault
    与我在
    .cs
    中运行的
    powershell
    程序集成。 https://learn.microsoft.com/en-us/azure/cosmos-db/store-credentials-key-vault

azure-cosmosdb azure-keyvault azure-cosmosdb-sqlapi
2个回答
0
投票

我知道部分答案。要使用环境变量,我需要

using CosmosClient client = new(
    accountEndpoint: Environment.GetEnvironmentVariable("COSMOS_ENDPOINT")!,
    authKeyOrResourceToken: Environment.GetEnvironmentVariable("COSMOS_KEY")!
);

答案在https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/how-to-dotnet-get-started?tabs=azure-cli%2Cwindows#connect-to- azure-cosmos-db-sql-api

我还不知道怎么用

key vault
.


0
投票

失败与 Cosmos DB 无关。

失败与正在运行的应用程序无法获取MSI令牌有关

at Azure.Identity.ManagedIdentitySource.HandleResponseAsync(Boolean async, TokenRequestContext context, Response response, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentitySource.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentityClient.AuthenticateCoreAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentityClient.AppTokenProviderImpl(AppTokenProviderParameters parameters)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.SendTokenRequestToProviderAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.FetchNewAccessTokenAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.ClientCredentialRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.ConfidentialClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenForClientParameters clientParameters, CancellationToken cancellationToken)
   at Azure.Identity.AbstractAcquireTokenParameterBuilderExtensions.ExecuteAsync[T](AbstractAcquireTokenParameterBuilder`1 builder, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientCoreAsync(String[] scopes, String tenantId, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.MsalConfidentialClient.AcquireTokenForClientAsync(String[] scopes, String tenantId, Boolean async, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentityClient.AuthenticateAsync(Boolean async, TokenRequestContext context, CancellationToken cancellationToken)
   at Azure.Identity.ManagedIdentityCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)
   

Cosmos DB SDK 尝试调用 Azure Identity 以获取要发送的令牌以使用 Cosmos DB 进行身份验证,但调用在 Azure Identity 上失败。

您正在使用

new DefaultAzureCredential()
,这是一种代币。

你的应用程序应该在 Azure 的某个地方运行(你不能在你的机器本地使用 DefaultAzureCredential)并且根据你运行的环境,有不同的故障排除步骤。错误消息包含一个 URL,用于访问每个环境的相关信息:https://aka.ms/azsdk/net/identity/managedidentitycredential/troubleshoot

如果您正在使用

new DefaultAzureCredential()
在您的计算机上运行,这就是此错误的来源。

© www.soinside.com 2019 - 2024. All rights reserved.