首页 > 解决方案 > Azure:通过证书从云工作者连接到密钥保管库

问题描述

我有一个工作进程作为 Azure 中的经典云服务运行。此过程需要从 Azure 密钥保管库中检索一个值,并且我需要将保管库身份验证机密保存在我的源树之外。

托管身份似乎不适用于经典云工作者,因此我正在查看证书。通过创建证书然后在 Azure Active Directory 中上传以进行我的应用程序注册,我已经通过证书获得身份验证以在本地工作:

证书创建:

New-SelfSignedCertificate -Subject "CN=MyFineCertificate" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature

使用它连接到密钥保管库的代码(在本地工作):

private static KeyVaultClient GetClient()
{
    var certificate = GetCertificate();
    var assertion = new ClientAssertionCertificate(clientId, certificate);
    var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback((a, r, s) => GetAccessTokenUsingCert(a, r, s, assertion)));
    return client;
}

private static X509Certificate2 GetCertificate()
{
    var certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    certStore.Open(OpenFlags.ReadOnly);
    var results = certStore.Certificates.Find(/* criteria */);
    return results[0];
}

private static async Task<string> GetAccessToken(string authority, string resource, string scope, ClientAssertionCertificate cert)
{
    var authContext = new AuthenticationContext(authority, TokenCache.DefaultShared);
    var result = await authContext.AcquireTokenAsync(resource, cert);
    return result.AccessToken;
}

到目前为止,一切都很好。但是,我希望我的 Azure 云工作者能够执行此操作,因此我需要在那里提供我的证书。我天真的假设是,我可以从门户中我的云工作者的“证书”面板上传证书 (pfx)。

不幸的是,我的云工作者无法找到它。如果我在 Azure 上运行它,上传我的证书后,它不会显示:

foreach (StoreName name in Enum.GetValues(typeof(StoreName)))
{
    foreach (StoreLocation location in Enum.GetValues(typeof(StoreLocation)))
    {
        var certStore = new X509Store(name, location);
        certStore.Open(OpenFlags.ReadOnly);
        foreach (var res in certStore.Certificates)
        {
            /* log certificate */
        }
    }
}

为什么不显示?我是否走在正确的轨道上,还是我完全误解了它的工作原理?

标签: c#azureazure-cloud-servicesx509certificate2azure-keyvault

解决方案


您的问题有两个部分:

  1. 方法- 由于云服务不提供托管服务标识,如何使用 Azure Key Vault 进行工作/身份验证?

    你在正确的轨道上。我已经在此 SO 帖子中描述了使用 Key Vault 的类似问题的方法 -在 Azure 云服务配置中保护敏感信息

  2. 实施- 具体如何从云服务角色实例访问自签名证书。

    我认为您可能缺少指定证书及其在云服务定义和配置文件中的位置。你应该尝试添加这样的东西 -

    CSCFG

     <Certificates>
         <Certificate name="MyFineCertificate" thumbprint="<my_thumbprint>" thumbprintAlgorithm="<my_thumbprint_algo e.g. sha1>" />
     </Certificates>
    

    CSDEF

     <Certificates>
          <Certificate name="MyFineCertificate" storeLocation="LocalMachine" storeName="My" />
     </Certificates> 
    

    请注意,我已将商店位置称为 LocalMachine。现在,您应该能够通过指定正确的位置从您的代码访问证书。

    var certStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    

推荐阅读