Connect Azure CosmosDB using Managed Identities from Azure Function App both locally and on Azure

PingpongSet 36 Reputation points
2022-02-17T11:09:42.01+00:00

I create a Managed Identity for a Function app and assigned it to DocumentDB Account Contributor by following the two sections below

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#assign-a-system-assigned-managed-identity-to-a-function-app

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#grant-access-to-your-azure-cosmos-account

Microsoft.Azure.Services.AppAuthentication

I got an exception when I tried to run the code from the section below:

https://learn.microsoft.com/en-us/azure/cosmos-db/managed-identity-based-authentication#programmatically-access-the-azure-cosmos-db-keys

Could not load file or assembly 'System.Text.Encodings.Web,
Version=6.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
The system cannot find the file specified.
at
System.Text.Json.Serialization.Metadata.JsonPropertyInfo.DeterminePropertyName()
at
System.Text.Json.Serialization.Metadata.JsonPropertyInfo.GetPolicies(Nullable1 ignoreCondition, Nullable1 declaringTypeNumberHandling) at
...
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at
Cosmos.Samples.AzureFunctions.AzureFunctionsCosmosClientMI.<Run>d__7.MoveNext()
in
C:.ME\MyLab.Code\AzureCode\CosmosDB\azure-cosmos-dotnet-v3-usage\AzureFunctions\AzureFunctionsCosmosClientMI.cs:line
85

Azure.Identity

Since AppAuthentication is not recommended by MS, then I switched to using Azure.Identity by following the links below:
https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet

https://joonasaijala.com/2021/07/01/how-to-using-managed-identities-to-access-cosmos-db-data-via-rbac-and-disabling-authentication-via-keys/

and the code below

 static string cosmosUrl = "https://xxx.documents.azure.com:443/";  
    private static CosmosClient client = new CosmosClient(cosmosUrl, new DefaultAzureCredential());  
   var container = client.GetContainer("FamilyDatabase", "FamilyContainer");  
        try  
        {  
            var result = await container.CreateItemAsync<Item>(data, new PartitionKey(data.LastName));  
            return new OkObjectResult(result.Resource.Id);  
        }  
        catch (CosmosException cosmosException)  
        {  
            log.LogError("Creating item failed with error {0}", cosmosException.ToString());  
            return new BadRequestObjectResult($"Failed to create item. Cosmos Status Code {cosmosException.StatusCode}, Sub Status Code {cosmosException.SubStatusCode}: {cosmosException.Message}.");  
        }  

However, I got the exception below both locally and running it in Azure.

Failed to create item. Cosmos Status Code Forbidden, Sub Status Code
5301: Response status code does not indicate success: Forbidden (403);
Substatus: 5301; ActivityId: xxxx-bf03-4355-8642-5d316f9d3373;
Reason: (Request blocked by Auth xxxx : Request is blocked because
principal [xxx-2bff-44e9-97be-9ffeb3aae3ee] does not have
required RBAC permissions to perform action
[Microsoft.DocumentDB/databaseAccounts/readMetadata] on resource [/].
Learn more: https://aka.ms/cosmos-native-rbac. ActivityId:
xxx-bf03-4355-8642-5d316f9d3373,
Microsoft.Azure.Documents.Common/2.14.0, Windows/10.0.14393
cosmos-netstandard-sdk/3.24.1);.

Locally, I logged into VS following the link
https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#authenticating-via-visual-studio

Any idea for resolving issues with Azure.Identity?

Ref:

https://stackoverflow.com/questions/67512766/connect-function-app-to-cosmosdb-with-managed-identity

Azure Functions
Azure Functions
An Azure service that provides an event-driven serverless compute platform.
4,917 questions
Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,615 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
21,466 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.