Hi @MughundhanRaveendran-MSFT
I've got exactly the same problem here, and stuck a bit already. Can provide the details I have.
My account has the following roles assigned on Cosmos DB account instance:
- Owner
- [DocumentDB Account Contributor](https://portal.azure.com/#"DocumentDB Account Contributor")
- [Cosmos DB Operator](https://portal.azure.com/#"Cosmos DB Operator")
- [Cosmos DB Account Reader Role](https://portal.azure.com/#"Cosmos DB Account Reader Role")
- [Managed Application Contributor Role](https://portal.azure.com/#"Managed Application Contributor Role")
- [Support Request Contributor](https://portal.azure.com/#"Support Request Contributor")
- [Custom - Contributor](https://portal.azure.com/#"Custom - Contributor")
- [Custom - Register Microsoft providers](https://portal.azure.com/#"Custom - Register Microsoft providers")
As you can see, I've already assigned almost every role I could think of, - but it didn't help.
Using the same account in Azure Data Studio, - I can view Cosmos database, and create documents, - so I assume the issue is NOT with permissions themselves.
On the other hand, using exactly the same Visual Studio instance (with same account logged in), - I successfully connected to Azure SQL, Storage Account (BLOB, Table, Queue), ServiceBus, and EventHub - all fine and easy. But Cosmos DB is an enigma...
Here is how I do DI registration of the connection (sadly, there is no built-in extension for Cosmos in Microsoft.Extensions.Azure namespace):
builder.Services.AddAzureClients(b =>
{
b.AddClient<CosmosClient, CosmosClientOptions>((options, credential) =>
new CosmosClientBuilder("https://[mycosmosname].documents.azure.com:443/", credential)
.WithApplicationName("TestApp")
.Build())
.WithCredential(new DefaultAzureCredential())
.WithName("TestCosmos");
});
and this is how it's used:
`[ApiController]`
[Route("[controller]")]
public class TestController : ControllerBase
{
readonly IAzureClientFactory<CosmosClient> _cosmosClientFactory;
public TestController(
IAzureClientFactory<CosmosClient> cosmosClientFactory)
{
_cosmosClientFactory = cosmosClientFactory;
}
[HttpPost]
[Route("cosmos")]
public async Task<string> CreateCosmosDoc()
{
var client = _cosmosClientFactory.CreateClient("TestCosmos");
var database = client.GetDatabase("db1");
var container = database.GetContainer("container1");
await container.CreateItemAsync(new { Prop = "Hello World!", Time = DateTime.Now.ToString("s") }, new PartitionKey("test-partition"));
return "Success";
}
}
And full error text is:
Microsoft.Azure.Cosmos.CosmosException : Response status code does not indicate success: Forbidden (403); Substatus: 5301; ActivityId: 00000000-0000-0000-0000-000000000000; Reason: ({"code":"Forbidden","message":"Request blocked by Auth cosmos-opst-test : Request is blocked because principal [......] does not have required RBAC permissions to perform action [Microsoft.DocumentDB/databaseAccounts/readMetadata] on resource [/]. Learn more: https://aka.ms/cosmos-native-rbac.This could be because the user's group memberships were not present in the AAD token.\r\nActivityId: {...guid...}, Microsoft.Azure.Documents.Common/2.14.0"}
RequestUri: https://[mycosmosname].documents.azure.com/;
RequestMethod: GET;
Header: Authorization Length: 2174;
Header: Cache-Control Length: 8;
Header: User-Agent Length: 85;
Header: x-ms-version Length: 10;
Header: x-ms-cosmos-sdk-supportedcapabilities Length: 1;
Header: Accept Length: 16;
Header: traceparent Length: 55;
, Request URI: /, RequestStats: , SDK: Windows/10.0.19045 cosmos-netstandard-sdk/3.36.0);
at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetOnlyGlobalEndpointAsync()
at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetAccountPropertiesHelper.GetAccountPropertiesAsync()
at Microsoft.Azure.Cosmos.Routing.GlobalEndpointManager.GetDatabaseAccountFromAnyLocationsAsync(Uri defaultEndpoint, IList`1 locations, IList`1 accountInitializationCustomEndpoints, Func`2 getDatabaseAccountFn, CancellationToken cancellationToken)
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.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.AsyncCacheNonBlocking`2.GetAsync(TKey key, Func`2 singleValueInitFunc, Func`2 forceRefresh)
at Microsoft.Azure.Cosmos.DocumentClient.EnsureValidClientAsync(ITrace trace)
--- Cosmos Diagnostics ---{"Summary":{},"name":"CreateItemAsync","start datetime":"2024-09-25T14:58:30.055Z","duration in milliseconds":516.9528,"data":{"Client Configuration":{"Client Created Time Utc":"2024-09-25T14:58:28.5184085Z","MachineId":"hashedMachineName:c83eaf77-d872-8bb8-da4d-aad473ad757f","NumberOfClientsCreated":1,"NumberOfActiveClients":1,"ConnectionMode":"Direct","User Agent":"cosmos-netstandard-sdk/3.43.1|1|X64|Microsoft Windows 10.0.19045|.NET 8.0.8|N|TestApp","ConnectionConfig":{"gw":"(cps:50, urto:6, p:False, httpf: False)","rntbd":"(cto: 5, icto: -1, mrpc: 30, mcpe: 65535, erd: True, pr: ReuseUnicastPort)","other":"(ed:False, be:False)"},"ConsistencyConfig":"(consistency: NotSet, prgns:[], apprgn: )","ProcessorCount":16}},"children":[{"name":"ItemSerialize","duration in milliseconds":10.7522},{"name":"Microsoft.Azure.Cosmos.Handlers.RequestInvokerHandler","duration in milliseconds":492.6261,"children":[{"name":"Waiting for Initialization of client to complete","duration in milliseconds":478.6111}]}]}
HEADERS
=======
Accept: text/plain
Host: localhost:7138
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36
Accept-Encoding: gzip, deflate, br, zstd
Accept-Language: en-US,en;q=0.9
Origin: https://localhost:7138
Referer: https://localhost:7138/swagger/index.html
Content-Length: 0
sec-ch-ua-platform: "Windows"
sec-ch-ua: "Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"
sec-ch-ua-mobile: ?0
sec-fetch-site: same-origin
sec-fetch-mode: cors
sec-fetch-dest: empty
priority: u=1, i