gorrch
gorrch

Reputation: 551

Create database inside Azure Cosmos DB account with RBAC

I use java version 4 SDK for azure cosmos db. I want to create database inside azure cosmos db account with service principal, not with masterkey.

I assigned to service principal DocumentDB Account Contributor and Cosmos DB Operator built-in-role definitions, according to this documentation:

https://learn.microsoft.com/pl-pl/azure/role-based-access-control/built-in-roles#cosmos-db-operator

I was not able to create CosmosAsyncClient, until I added new custom role, which just contains reading metadata. Above mentioned built-in-role definitions do not contain it...

 TokenCredential ServicePrincipal = new ClientSecretCredentialBuilder()
            .authorityHost("https://login.microsoftonline.com")
            .tenantId(tenant_here)
            .clientId(clientid_here)
            .clientSecret(secret_from_above_client)
            .build();

 client = new CosmosClientBuilder()
                            .endpoint(AccountSettings.HOST)
                            .credential(ServicePrincipal)
                            .buildAsyncClient();

After I added this role, client was created, but I am not able to create database instance and also container inside it as next step. In access control I can see that roles are assigned so service principal is correct here.

What is more, when firstly I create database and container with master key and then I want to read/write data using service principal, it works (obviously after adding custom role for writting also).

Then I do not know why DocumentDB Account Contributor and Cosmos DB Operator does not work for creation database.

Upvotes: 1

Views: 2858

Answers (1)

Joy Wang
Joy Wang

Reputation: 42103

Looks it is a bug in java SDK, the DocumentDB Account Contributor role is enough to create the database and container as it has the Microsoft.DocumentDb/databaseAccounts/* permission(* is a wildcard, it also includes the Microsoft.DocumentDB/databaseAccounts/readMetadata you mentioned).

When I test to use a service principal with this role to create the database with the powershell New-AzCosmosDBSqlDatabase, it works fine. When using the service principal to run this command, it essentially uses the Azure AD client credential flow to get the token, then uses the token to call the REST API - PUT https://management.azure.com/subscriptions/xxxx/resourceGroups/xxxx/providers/Microsoft.DocumentDB/databaseAccounts/xxxx/sqlDatabases/testdb1?api-version=2020-04-01 to create the database, the java SDK essentially also does the same thing, so it should also work.

Upvotes: 1

Related Questions