gpt4 book ai didi

c# - 如何调试 ProtectKeysWithAzureKeyVault?

转载 作者:行者123 更新时间:2023-12-02 07:46:31 25 4
gpt4 key购买 nike

尝试使用ProtectKeysWithAzureKeyVault时,出现以下错误:

00:01:41 ERR] An error occurred while reading the key ring. Microsoft.Azure.KeyVault.Models.KeyVaultErrorException: Operation returned an invalid status code 'Forbidden' at Microsoft.Azure.KeyVault.KeyVaultClient.WrapKeyWithHttpMessagesAsync(String vaultBaseUrl, String keyName, String keyVersion, String algorithm, Byte[] value, Dictionary`2 customHeaders, CancellationToken cancellationToken) at Microsoft.Azure.KeyVault.KeyVaultClientExtensions.WrapKeyAsync(IKeyVaultClient operations, String keyIdentifier, String algorithm, Byte[] key, CancellationToken cancellationToken) at Microsoft.AspNetCore.DataProtection.AzureKeyVault.AzureKeyVaultXmlEncryptor.EncryptAsync(XElement plaintextElement) at Microsoft.AspNetCore.DataProtection.AzureKeyVault.AzureKeyVaultXmlEncryptor.Encrypt(XElement plaintextElement) at Microsoft.AspNetCore.DataProtection.XmlEncryption.XmlEncryptionExtensions.EncryptIfNecessary(IXmlEncryptor encryptor, XElement element) at Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.IInternalXmlKeyManager.CreateNewKey(Guid keyId, DateTimeOffset creationDate, DateTimeOffset activationDate, DateTimeOffset expirationDate) at Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager.CreateNewKey(DateTimeOffset activationDate, DateTimeOffset expirationDate) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.CreateCacheableKeyRingCore(DateTimeOffset now, IKey keyJustAdded) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.Microsoft.AspNetCore.DataProtection.KeyManagement.Internal.ICacheableKeyRingProvider.GetCacheableKeyRing(DateTimeOffset now) at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingProvider.GetCurrentKeyRingCore(DateTime utcNow)

我正在尝试使用这样的方法:

            services.AddDataProtection()
.SetApplicationName("APPLICATIONNAME")
.PersistKeysToAzureBlobStorage(container, "keys.xml")
.ProtectKeysWithAzureKeyVault(KeyVaultClientFactory.Create(), "https://KEYVAULTNAME.vault.azure.net/keys/DATAPROTECTIONKEY/");

我检查过的事情:

  1. KeyVault 中的应用程序具有包装/展开权限(我已启用所有权限只是为了尝试使其正常工作)
  2. 上面的代码无需 ProtectKeysWithAzureKeyVault 即可运行
  3. KeyVaultClientFactory.Create() 返回可以检索 secret 的有效 KeyVault
  4. (RSA) key 已启用并存在于 KeyVault 中 - 对该 key 允许的操作也已全部启用。

我现在不知道如何进一步调试它。我想我错过了一些明显的东西,欢迎任何建议/建议!

最佳答案

我建议您更改实现,如下所示:

{
"DataProtection": {
"KeyVaultKeyId": "https://mykeyvaultname.vault.azure.net/keys/DataProtectionKey/bfc1bda979bc4081b89ab6f43bad12b8"
}
}

var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(_tokenProvider.KeyVaultTokenCallback));

services.AddDataProtection()
.ProtectKeysWithAzureKeyVault(kvClient, settings.KeyVaultKeyId);

并请确保为应用提供对 key 保管库的解包 key 和包装 key 权限。请注意,授予许可后需要一段时间才能反射(reflect)更改。

您可以在此处查看引用代码:

https://github.com/aspnet/AspNetCore/blob/6f197a9e5d08477b598826e0d028019c9d62ad82/src/DataProtection/AzureKeyVault/src/AzureDataProtectionBuilderExtensions.cs

其他引用:

https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-2.2

https://joonasw.net/view/using-azure-key-vault-and-azure-storage-for-asp-net-core-data-protection-keys

这就是我的startup.cs的样子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using KeyVaultSample.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.DataProtection.AzureStorage;


using Microsoft.WindowsAzure.Storage.Blob;
using Microsoft.Rest;
using Microsoft.WindowsAzure.Storage.Auth;

namespace KeyVaultSample
{
public class DataProtectionSettings
{
public string KeyVaultKeyId { get; set; }
public string AadTenantId { get; set; }
public string StorageAccountName { get; set; }
public string StorageKeyContainerName { get; set; }
public string StorageKeyBlobName { get; set; }
}
public class Startup
{
private readonly AzureServiceTokenProvider _tokenProvider;

public Startup(IConfiguration configuration)
{
Configuration = configuration;
_tokenProvider = new AzureServiceTokenProvider();
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});

var settings = Configuration.GetSection("DataProtection").Get<DataProtectionSettings>();

var kvClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(_tokenProvider.KeyVaultTokenCallback));

services.AddDataProtection()
.ProtectKeysWithAzureKeyVault(kvClient, settings.KeyVaultKeyId);
// Replicates PersistKeysToAzureBlobStorage
// There is no overload to give it the func it ultimately uses
// We need to do that so that we can get refreshed tokens when needed
services.Configure<KeyManagementOptions>(options =>
{
options.XmlRepository = new AzureBlobXmlRepository(() =>
{
// This func is called every time before getting the blob and before modifying the blob
// Get access token for Storage
// User / managed identity needs Blob Data Contributor on the Storage Account (container was not enough)
string accessToken = _tokenProvider.GetAccessTokenAsync("https://storage.azure.com/", tenantId: settings.AadTenantId)
.GetAwaiter()
.GetResult();
// Create blob reference with token
var tokenCredential = new TokenCredential(accessToken);
var storageCredentials = new StorageCredentials(tokenCredential);
var uri = new Uri($"https://{settings.StorageAccountName}.blob.core.windows.net/{settings.StorageKeyContainerName}/{settings.StorageKeyBlobName}");
// Note this func is expected to return a new instance on each call
var blob = new CloudBlockBlob(uri, storageCredentials);
return blob;
});
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<IdentityUser>()
.AddDefaultUI(UIFramework.Bootstrap4)
.AddEntityFrameworkStores<ApplicationDbContext>();


services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseAuthentication();

app.UseMvc();
}
}
}

希望有帮助。

关于c# - 如何调试 ProtectKeysWithAzureKeyVault?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57965388/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com