问题
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