Getting/resetting Azure Cosmos DB Master Keys Programmatically

点点圈 提交于 2021-01-29 20:48:11

问题


I am trying to get and reset the master keys for an Azure Cosmos DB account from code, specifically from C# code in an Azure Function App whose system assigned managed identity has an RBAC role defined on the Cosmos DB account. The Cosmos DB client api does not appear to have this functionality.


回答1:


Here is an example on how to generate the master key from the github repo.

private static string GenerateMasterKeyAuthorizationSignature(string verb, string resourceId, string resourceType, string key, string keyType, string tokenVersion)
{
    var hmacSha256 = new System.Security.Cryptography.HMACSHA256 { Key = Convert.FromBase64String(key) };

    string payLoad = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}\n{1}\n{2}\n{3}\n{4}\n",
            verb.ToLowerInvariant(),
            resourceType.ToLowerInvariant(),
            resourceId,
            utc_date.ToLowerInvariant(),
            ""
    );

    byte[] hashPayLoad = hmacSha256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(payLoad));
    string signature = Convert.ToBase64String(hashPayLoad);

    return System.Web.HttpUtility.UrlEncode(String.Format(System.Globalization.CultureInfo.InvariantCulture, "type={0}&ver={1}&sig={2}",
        keyType,
        tokenVersion,
        signature));
}



回答2:


You can do this using Azure Management Fluent API. You need to include this nuget package "Microsoft.Azure.Management.Fluent". Here is the link

Below is the sample code for the same.

    var credentials = SdkContext.AzureCredentialsFactory
                            .FromServicePrincipal(clientId,
                            clientSecret,
                            tenantId,
                            AzureEnvironment.AzureGlobalCloud);

    IAzure azure = Azure.Authenticate(credentials).WithSubscription("<<Your subscription Id>>");
    var cosmosaccount = azure.CosmosDBAccounts.GetByResourceGroup("<<Your cosmos account resource group name>>", "<<Your cosmos account name>>");

    Console.WriteLine(cosmosaccount.ListKeys().SecondaryMasterKey);
    cosmosaccount.RegenerateKey("secondary");
    Console.WriteLine(cosmosaccount.ListKeys().SecondaryMasterKey); 


来源:https://stackoverflow.com/questions/58248538/getting-resetting-azure-cosmos-db-master-keys-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!