![](/img/trans.png)
[英]Unable to connect to Azure Cosmos DB using the MongoDB Driver .Net C#
[英]How to connect to azure cosmos db account in a c# code without using primary key
我一直在嘗試連接到 Azure Cosmos DB 帳戶。 實際目的是獲取用於測試目的的密鑰。 所以我不能使用密鑰登錄到 cosmos DB 帳戶。
我在網上找到了使用主鍵登錄的方法,但這不是我的目標。 此外,我發現這種使用 Fluent SDK 的堆棧溢出方法,但它對我不起作用。 以編程方式獲取 azure cosmos DB 密鑰
我在這里找到了另一種基於證書的身份驗證方式 - Certificate Based authentication for cosmos db
我遇到了這個獲取主鍵的命令,但問題是我無法通過不允許我獲取密鑰的 c# 代碼連接到 azure cosmos DB 帳戶。
var cosmosPrimaryKey = _accountCosmosDBProvider.GetPrimaryKey(rgName, accountName, CancellationToken.None);
有沒有人知道如何進行相同的操作?
根據資料,我這邊做個測試。 我們可以使用以下步驟來獲取私鑰。
$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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.