无法从桌面控制台应用访问 Azure Key Vault

Can't Access Azure Key Vault from desktop console app

我无法从 Azure 密钥保管库访问机密。我怀疑问题是我没有充分理解术语,所以我提供给各种 API 调用的参数是错误的。

这是我使用的基本代码:

    protected async Task<string> GetCommunityKeyAsync( UserConfiguration user )
    {
        var client = new KeyVaultClient( 
            new KeyVaultClient.AuthenticationCallback( GetAccessTokenAsync ),
            new HttpClient() );

        // user.VaultUrl is the address of my key vault
        // e.g., https://previously-created-vault.vault.azure.net
        var secret = await client.GetSecretAsync( user.VaultUrl, "key-to-vault-created-in-azure-portal" );

        return secret.Value;
    }

    private async Task<string> GetAccessTokenAsync( string authority, string resource, string scope )
    {
        var context = new AuthenticationContext( authority, TokenCache.DefaultShared );

        // this line throws a "cannot identify user exception; see
        // below for details
        var result =
            await context.AcquireTokenAsync( resource, "id-of-app-registered-via-azure-portal", new UserCredential() );

        return result.AccessToken;
    }

这是抛出的异常:

Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException
HResult=0x80131500 Message=unknown_user: Could not identify logged in user Source=Microsoft.IdentityModel.Clients.ActiveDirectory
StackTrace: at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenNonInteractiveHandler.d__4.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__57.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__37.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions.d__0.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at NextDoorScanner.ScannerJob.<GetAccessTokenAsync>d__21.MoveNext() in C:\Programming\CommunityScanner\CommunityScanner\ScannerJob.cs:line 197 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Azure.KeyVault.KeyVaultCredential.d__9.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Azure.KeyVault.KeyVaultCredential.<ProcessHttpRequestAsync>d__10.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()<br> at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Azure.KeyVault.KeyVaultClient.<GetSecretWithHttpMessagesAsync>d__65.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()<br> at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.d__11.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at NextDoorScanner.ScannerJob.<GetCommunityKeyAsync>d__20.MoveNext() in C:\Programming\CommunityScanner\CommunityScanner\ScannerJob.cs:line 188 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at NextDoorScanner.NextDoorScannerJob.d__4.MoveNext() in C:\Programming\CommunityScanner\CommunityScanner\NextDoorScannerJob.cs:line 46 at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at NextDoorScanner.Program.Main(String[] args) in C:\Programming\CommunityScanner\CommunityScanner\Program.cs:line 22

我做了一些配置,我认为涉及通过 powershell 将我的桌面注册为 Azure 用户:

Login-AzureRmAccount
// as I recall, this next line complained about the app ID already being   defined
New-AzureRmADServicePrincipal -ApplicationId 'id-of-app-previously-defined-via-azure-portal'
Set-AzureRmKeyVaultAccessPolicy -VaultName 'vault-name' -ServicePrincipalName id-of-app-previously-defined-via-azure-portal -PermissionsToSecrets Get

我不清楚我是否应该向 GetSecretAsync() 提供保险库密钥。我还想知道除了将新创建的 UserCredential 传递给 AcquireTokenAsync() 之外,我是否应该做其他事情。最后,我在网上看到有关创建用于密钥保管库的存储帐户的参考资料,我确实这样做了,但我没有创建保管库我正在使用 "in" 存储帐户。而且我没有在代码中识别存储帐户。

帮助或参考从控制台桌面应用程序访问密钥保管库的非常好的示例将不胜感激。

Help, or a reference to a really good example accessing key vaults from a console desktop app would be appreciated.

注册 Azure 目录应用程序后,我们需要 assign role to application. if we want to operate Azure Key Vault, we also need to give permission to operate Key Vault. The resource for key vault is https://vault.azure.net. You also could get more detail info from another

演示代码:

 static string appId = "application Id";
 static string tenantId = "tenant id";
 static string uri = "http://localhost:13526"; //redirect uri
 static void Main(string[] args)
 {
    var kv = new KeyVaultClient(GetAccessToken);
    var scret = kv.GetSecretAsync("https://xxxx.vault.azure.net", "xxxx").GetAwaiter().GetResult();
 }

 public static async Task<string> GetAccessToken(string azureTenantId,string clientId,string redirectUri)
 {
       var context = new AuthenticationContext("https://login.windows.net/" + tenantId);
       var tokenResult = await context.AcquireTokenAsync("https://vault.azure.net", appId, new Uri(uri), new PlatformParameters(PromptBehavior.SelectAccount));
       return tokenResult.AccessToken;
  }

除了 Tom 提供的内容之外,在我终于弄清楚如何让事情正常工作之后,我记录了我在 https://jumpforjoysoftware.com/2017/12/azure-key-vaults/ 上学到的东西。希望这一切都能让人们避免一些严重的挫败感。

Mark 的博客非常有帮助,从那个博客我学会了如何做,下面是截至 2018 年 11 月 6 日的步骤和代码。

步骤总结:

  1. 注册应用程序
  2. 在这个新注册的应用程序中创建密钥
  3. 创建 Key Vault 并为应用分配权限
  4. 在保险库中创建 Secret

通过代码访问它们

using Microsoft.Azure.KeyVault;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Experiments.AzureKeyValut
{
    internal class AzureKeyValueDemo
    {
        private static async Task Main(string[] args)
        {
            await GetSecretAsync("https://YOURVAULTNAME.vault.azure.net/", "YourSecretKey");
        }

        private static async Task<string> GetSecretAsync(string vaultUrl, string vaultKey)
        {
            var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessTokenAsync), new HttpClient());
            var secret = await client.GetSecretAsync(vaultUrl, vaultKey);

            return secret.Value;
        }

        private static async Task<string> GetAccessTokenAsync(string authority, string resource, string scope)
        {
            //DEMO ONLY
            //Storing ApplicationId and Key in code is bad idea :)
            var appCredentials = new ClientCredential("YourApplicationId", "YourApplicationKey");
            var context = new AuthenticationContext(authority, TokenCache.DefaultShared);

            var result = await context.AcquireTokenAsync(resource, appCredentials);

            return result.AccessToken;
        }
    }
}

如何注册您的应用:

如何创建 Azure 应用程序的密码并获取您的应用程序 ID

如何创建 Azure Key Vault 和分配权限

如何创建 Azure 机密

如何通过代码访问它

Here are the docs and samples 了解如何使用最新版本的 Azure SDK (Azure.Security.KeyVault.Secrets) 执行此操作。

以防万一,以下是一些其他受支持语言的相同文档:

Java

JavaScript

Python