Reputation: 3
I have been trying to connect to Azure Cosmos DB account. The actual aim is to get the keys for testing purposes. So I cannot use keys to login into the cosmos DB account.
I found approaches online which are using the primary key to login but that is not my aim. Further, I found this approach on stack overflow using fluent SDK but it is not working for me. Getting azure cosmos DB key programmatically
I found another way of certificate-based authentication here-Certificate Based authentication for cosmos db
I came across this command to fetch the primary key but the issue is that I am unable to connect to azure cosmos DB account through c# code which is not allowing me to fetch keys.
var cosmosPrimaryKey = _accountCosmosDBProvider.GetPrimaryKey(rgName, accountName, CancellationToken.None);
Does anyone have any idea on how to proceed for the same?
Upvotes: 0
Views: 2068
Reputation: 23111
According to the information, I do a test on my side. We can use the following steps to get the private key.
$cert = New-SelfSignedCertificate -CertStoreLocation "Cert:\CurrentUser\My" -Subject "CN=sampleAppCert" -KeySpec KeyExchange -KeyExportPolicy Exportable -NotAfter (Get-Date).AddYears(10) -NotBefore (Get-Date).AddYears(-1)
$bin = $cert.RawData
$base64Value = [System.Convert]::ToBase64String($bin)
Connect-AzureAD -TenantId "<your tenant id>"
$app=Get-AzureADApplication -ObjectId < the object id of the app you create>
New-AzureADApplicationKeyCredential -ObjectId 77bfe399-38db-4ce5-85b1-c79ef0ed5e5b -CustomKeyIdentifier "key12" -Value $base64Value -Type AsymmetricX509Cert -Usage Verify -EndDate $cert.NotAfter
# get the certificate
X509Certificate2 cert = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCollection = store.Certificates;
X509Certificate2Collection currentCerts = certCollection.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
X509Certificate2Collection signingCert = currentCerts.Find(X509FindType.FindBySubjectName, "sampleAppCert", false);
cert = signingCert.OfType<X509Certificate2>().OrderByDescending(c => c.NotBefore).FirstOrDefault();
store.Close();
# get the Azure CosmosDB Primary Master Key
string tenantId = "";
string clientId = "the Azure AD application appid";
string subscriptionId = "the subscription id";
string rgName = "";
string accountName = "";
var creds = SdkContext.AzureCredentialsFactory.FromServicePrincipal(
clientId,
cert,
tenantId,
AzureEnvironment.AzureGlobalCloud
);
var azure = Azure.Configure()
.Authenticate(creds)
.WithSubscription(subscriptionId);
var keys = azure.CosmosDBAccounts.ListKeys(rgName, accountName);
Console.WriteLine(keys.PrimaryMasterKey);
Console.ReadLine();
Upvotes: 2