且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-02 21:38:03

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

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.

步骤摘要:

  1. 注册应用
  2. 在此新注册的应用程序内创建密钥
  3. 创建Key Vault并为应用分配权限
  4. 在金库中创建秘密

通过代码访问它们

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密钥保管库和分配权限

如何创建Azure机密

如何通过代码访问它