Azure KeyVault到期日期更新

时间:2018-12-19 03:24:15

标签: azure azure-keyvault

是否可以通过Microsoft.Azure.KeyVault软件包在KeyVault中创建密钥的新版本而无需创建密钥的新版本?我可以在Azure门户中执行此操作,但是需要能够以编程方式执行此操作。

1 个答案:

答案 0 :(得分:4)

是的,可以在不创建新版本的情况下更新现有机密的失效日期。

这是快速又肮脏的示例C#代码。仔细查看正在调用的SecretAttributesclient.UpdateSecretAsync方法。

Expires是您需要设置的机密的属性。

我正在使用KeyVaultClientExtensions.UpdateSecretAsync Method

using Microsoft.Azure.KeyVault;
using Microsoft.Azure.KeyVault.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;

namespace UpdateKeyVaultSecret
{
    class Program
    {
        static void Main(string[] args)
        {
            UpdateSecretAttributes("https://rohitvault1.vault.azure.net/secrets/mysecret1").GetAwaiter().GetResult();

            Console.ReadLine();
        }


        private static async Task<string> GetAccessTokenAsync(string authority, string resource, string scope)
        {
            var authContext = new AuthenticationContext(authority);
            ClientCredential clientCred = new ClientCredential("<my-app-clientid>", "<my-app-client-secret>");
            AuthenticationResult result = await authContext.AcquireTokenAsync(resource, clientCred);

            if (result == null)
                throw new InvalidOperationException("Failed to obtain the JWT token");

            return result.AccessToken;
        }

        public static async Task<string> GetSecretFromVault(string secretKeyIdentifier)
        {
            var client = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(GetAccessTokenAsync),
                new System.Net.Http.HttpClient());

            var secret = await client.GetSecretAsync(secretKeyIdentifier).ConfigureAwait(false);

            return secret.Value;
        }

        public static async Task<string> UpdateSecretAttributes(string secretKeyIdentifier)
        {
            var client = new KeyVaultClient(
                new KeyVaultClient.AuthenticationCallback(GetAccessTokenAsync),
                new System.Net.Http.HttpClient());

            SecretAttributes attributes = new SecretAttributes();
        attributes.Expires = DateTime.UtcNow.AddDays(15);

            var secret = await client.UpdateSecretAsync(secretKeyIdentifier, null, attributes, null).ConfigureAwait(false);

            return secret.Value;
        }
    }
}

另一方面,还有其他编程选项。我只是简要地提到这些,因为问题很笼统,有人可能也会在这里寻找除C#以外的方法: