Last active
February 20, 2020 09:13
-
-
Save danigian/2314ec6e8301c35db998ba6a16bea1e1 to your computer and use it in GitHub Desktop.
CosmosDB authentication with Managed Identities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static async Task<RestClient> GetRestClientAsync() | |
{ | |
var azureServiceTokenProvider = new AzureServiceTokenProvider(); | |
var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").ConfigureAwait(false); | |
var restTokenCredentials = new Microsoft.Rest.TokenCredentials(accessToken); | |
var azCred = new AzureCredentials(restTokenCredentials, null, tenantId, AzureEnvironment.AzureGlobalCloud); | |
return RestClient.Configure().WithEnvironment(AzureEnvironment.AzureGlobalCloud).WithCredentials(azCred).Build(); | |
} | |
static async Task CosmosDBTest() | |
{ | |
var cosmosDBManagementClient = new CosmosDBManagementClient(await GetRestClientAsync()); | |
cosmosDBManagementClient.SubscriptionId = subscriptionId; | |
var cosmosResource = await cosmosDBManagementClient.DatabaseAccounts.GetWithHttpMessagesAsync(resourceGroupName,cosmosDBName); | |
//If the managed Identity has more "power" you could do a ListKeysWithHttpMessagesAsync and retrieve the "write"key too | |
var cosmosKeys = await cosmosDBManagementClient.DatabaseAccounts.ListReadOnlyKeysWithHttpMessagesAsync(resourceGroupName, cosmosDBName); | |
Console.WriteLine($"Primary key for cosmos account: {cosmosKeys.Body.PrimaryReadonlyMasterKey}"); | |
var cosmosClient = new CosmosClient(cosmosResource.Body.DocumentEndpoint, cosmosKeys.Body.PrimaryReadonlyMasterKey ); | |
var createDBOperation = await cosmosClient.CreateDatabaseIfNotExistsAsync(dbname); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<Project Sdk="Microsoft.NET.Sdk"> | |
<PropertyGroup> | |
<OutputType>Exe</OutputType> | |
<TargetFramework>netcoreapp3.1</TargetFramework> | |
</PropertyGroup> | |
<ItemGroup> | |
<PackageReference Include="Microsoft.Azure.Services.AppAuthentication" Version="1.4.0" /> | |
<PackageReference Include="Microsoft.Rest.ClientRuntime" Version="3.0.3" /> | |
<PackageReference Include="Microsoft.Azure.Cosmos" Version="3.6.0" /> | |
<PackageReference Include="Microsoft.Azure.Management.Fluent" Version="1.31.0" /> | |
<PackageReference Include="Microsoft.Azure.Management.CosmosDB.Fluent" Version="1.31.0" /> | |
</ItemGroup> | |
</Project> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment