Currently, I am using Access Keys to connect to Azure Cosmos DB via Java. The code I use for this is as follows :
CosmosClient client = new CosmosClientBuilder().endpoint(cosmosEndpoint).key(cosmosKey)
.preferredRegions(Collections.singletonList("East US 2")) .consistencyLevel(ConsistencyLevel.EVENTUAL).buildClient();
where cosmosEndpoint = "https://<cosmosdb_name>.documents.azure.com:443/"
and cosmosKey
is the Primary Key .
Now, we are asked to stop using the Access Keys for Cosmos DB. So I created a Service Principal and assigned it a role of DocumentDB Account Contributor
.
The updated code in Java is as follows :
TokenCredential ServicePrincipal = new ClientSecretCredentialBuilder().authorityHost("https://login.microsoftonline.com")
.tenantId(getTenantID())
.clientId(getClientId())
.clientSecret(getSecret())
.build();
CosmosClient client = new CosmosClientBuilder().endpoint(cosmosEndpoint).credential(ServicePrincipal)
.preferredRegions(Collections.singletonList("East US 2"))
.consistencyLevel(ConsistencyLevel.EVENTUAL).buildClient();
The above method is giving me the following error :
Client initialization failed. Check if the endpoint is reachable and if your auth token is valid
Do I need to change the role assigned? Or am I missing something? How can I achieve this?