How to Access Cosmos DB in Java using Managed Identity/Service principal ?

Aayush Suresh Jain 146 Reputation points
2023-01-10T12:16:20.213+00:00

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?

Azure Cosmos DB
Azure Cosmos DB
An Azure NoSQL database service for app development.
1,901 questions
{count} vote

1 answer

Sort by: Most helpful
  1. Sajeetharan 2,261 Reputation points Microsoft Employee
    2023-03-08T12:11:03.73+00:00

    The sample on the documentation should help,

    TokenCredential ServicePrincipal = new ClientSecretCredentialBuilder()
        .authorityHost("https://login.microsoftonline.com")
        .tenantId("<azure-ad-tenant-id>")
        .clientId("<client-application-id>")
        .clientSecret("<client-application-secret>")
        .build();
    CosmosAsyncClient Client = new CosmosClientBuilder()
        .endpoint("<account-endpoint>")
        .credential(ServicePrincipal)
        .build();
    
    1 person found this answer helpful.
    0 comments No comments

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.