繁体   English   中英

如何在不使用主键的情况下连接到 ac# 代码中的 azure cosmos db 帐户

[英]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);

有没有人知道如何进行相同的操作?

根据资料,我这边做个测试。 我们可以使用以下步骤来获取私钥。

  1. 注册 Azure AD 应用程序在此处输入图像描述 在此处输入图像描述

  2. 创建基于证书的凭据

$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 
  1. 配置你的 Azure Cosmos 帐户以使用新标识在此处输入图像描述

  2. 代码

            # 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM