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

Can#39;t Access Azure Key Vault from desktop console app(无法从桌面控制台应用访问 Azure Key Vault)
本文介绍了无法从桌面控制台应用访问 Azure Key Vault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在访问 Azure 密钥保管库中的机密时遇到问题.我怀疑问题在于我没有充分理解术语,所以我提供给各种 API 调用的参数是错误的.

这是我正在使用的基本代码:

 受保护的异步任务GetCommunityKeyAsync(用户配置用户){var 客户端 = 新的 KeyVaultClient(新的 KeyVaultClient.AuthenticationCallback(GetAccessTokenAsync),新的 HttpClient() );//user.VaultUrl 是我的密钥保管库的地址//例如,https://previously-created-vault.vault.azure.netvar secret = await client.GetSecretAsync(user.VaultUrl, "key-to-vault-created-in-azure-portal" );返回秘密.值;}私有异步任务<字符串>GetAccessTokenAsync(字符串权限,字符串资源,字符串范围){var context = new AuthenticationContext( authority, TokenCache.DefaultShared );//此行抛出无法识别用户异常;请参阅//下面有详细介绍变量结果 =等待 context.AcquireTokenAsync(资源,id-of-app-registered-via-azure-portal",新 UserCredential());返回结果.AccessToken;}

这是抛出的异常:

<块引用>

Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException
HResult=0x80131500 Message=unknown_user: 无法识别记录在用户源=Microsoft.IdentityModel.Clients.ActiveDirectory
堆栈跟踪:在Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenNonInteractiveHandler.d__4.MoveNext()在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__57.MoveNext()在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__37.MoveNext()在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions.d__0.MoveNext()在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()在 NextDoorScanner.ScannerJob.<GetAccessTokenAsync>d__21.MoveNext() 中C:ProgrammingCommunityScannerCommunityScannerScannerJob.cs:line197 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()在Microsoft.Azure.KeyVault.KeyVaultCredential.d__9.MoveNext()在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()在Microsoft.Azure.KeyVault.KeyVaultCredential.<ProcessHttpRequestAsync>d__10.MoveNext()在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在Microsoft.Azure.KeyVault.KeyVaultClient.<GetSecretWithHttpMessagesAsync>d__65.MoveNext()在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在System.Runtime.CompilerServices.ConfiguredTaskAwaitable
1.ConfiguredTaskAwaiter.GetResult()在Microsoft.Azure.KeyVault.KeyVaultClientExtensions.d__11.MoveNext()在 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()在 NextDoorScanner.ScannerJob.<GetCommunityKeyAsync>d__20.MoveNext()在 C:ProgrammingCommunityScannerCommunityScannerScannerJob.cs:line188 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在 System.Runtime.CompilerServices.TaskAwaiter1.GetResult()在 NextDoorScanner.NextDoorScannerJob.d__4.MoveNext() 中C:ProgrammingCommunityScannerCommunityScannerNextDoorScannerJob.cs:line46 在System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() 在System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()在 NextDoorScanner.Program.Main(String[] args) 中C:ProgrammingCommunityScannerCommunityScannerProgram.cs:第 22 行

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

<块引用>

登录-AzureRmAccount//我记得,下一行抱怨应用 ID 已经被定义新 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 获取

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

如果您能提供帮助或参考从控制台桌面应用程序访问密钥保管库的非常好的示例,我们将不胜感激.

解决方案

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

步骤总结:

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

通过代码访问它们

使用 Microsoft.Azure.KeyVault;使用 Microsoft.IdentityModel.Clients.ActiveDirectory;使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Net.Http;使用 System.Text;使用 System.Threading.Tasks;命名空间 Experiments.AzureKeyValut{内部类 AzureKeyValueDemo{私有静态异步任务 Main(string[] args){await GetSecretAsync("https://YOURVAULTNAME.vault.azure.net/", "YourSecretKey");}私有静态异步任务<字符串>GetSecretAsync(字符串 vaultUrl,字符串 vaultKey){var client = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(GetAccessTokenAsync), new HttpClient());var secret = await client.GetSecretAsync(vaultUrl, vaultKey);返回秘密.值;}私有静态异步任务<字符串>GetAccessTokenAsync(字符串权限、字符串资源、字符串范围){//仅演示//在代码中存储 ApplicationId 和 Key 是个坏主意 :)var appCredentials = new ClientCredential("YourApplicationId", "YourApplicationKey");var context = new AuthenticationContext(authority, TokenCache.DefaultShared);var result = await context.AcquireTokenAsync(resource, appCredentials);返回结果.AccessToken;}}}

如何注册您的应用:

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

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

如何创建 Azure 机密

如何通过代码访问它

I am having trouble accessing a secret from an Azure key vault. I suspect the problem is that I don't adequately understand the terminology, so the arguments I'm supplying to various API calls are wrong.

Here's the basic code I'm using:

    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;
    }

Here is the exception that gets thrown:

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:ProgrammingCommunityScannerCommunityScannerScannerJob.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()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Azure.KeyVault.KeyVaultClient.<GetSecretWithHttpMessagesAsync>d__65.MoveNext() at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable
1.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:ProgrammingCommunityScannerCommunityScannerScannerJob.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:ProgrammingCommunityScannerCommunityScannerNextDoorScannerJob.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:ProgrammingCommunityScannerCommunityScannerProgram.cs:line 22

I did some configuration, I thought involving registering my desktop as an Azure user, via powershell:

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

I'm unclear if I'm supposed to be providing the vault key to GetSecretAsync(). I also wonder if I'm supposed to be doing something other than passing a newly-created UserCredential to AcquireTokenAsync(). Finally, I see references online to creating a storage account for use with key vaults, which I did, but I didn't create the vault I'm using "in" a storage account. And I'm not identifying the storage account in the code.

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

解决方案

Mark's blog was extremely helpful, from that blog I learnt how to do it and below are the steps and code as of 6-Nov-2018.

Summary of the steps:

  1. Register App
  2. Create Key inside this newly registered App
  3. Create Key Vault and Assign permission to the app
  4. Create Secret inside the vault

Access them thru code

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;
        }
    }
}

How to register your app:

How to create Azure App's password and get your App's Id

How to create Azure Key Vault and Assign Permissions

How to create Azure secrets

How to access it thru code

这篇关于无法从桌面控制台应用访问 Azure Key Vault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to MOQ an Indexed property(如何最小起订量索引属性)
Mocking generic methods in Moq without specifying T(在 Moq 中模拟泛型方法而不指定 T)
How Moles Isolation framework is implemented?(Moles Isolation 框架是如何实现的?)
Difference between Dependency Injection and Mocking Framework (Ninject vs RhinoMocks or Moq)(依赖注入和模拟框架之间的区别(Ninject vs RhinoMocks 或 Moq))
How to mock Controller.User using moq(如何使用 moq 模拟 Controller.User)
How do I mock a class without an interface?(如何模拟没有接口的类?)