gpt4 book ai didi

c# - Azure Active Directory 应用服务无法使用用户凭据/ token 连接到 Azure Keyvault

转载 作者:行者123 更新时间:2023-12-02 23:23:10 29 4
gpt4 key购买 nike

我正在尝试创建一个 Web 应用程序,用户可以在其中探索其 Azure 广告帐户明确有权访问的 Azure Keyvault secret 信息。它本质上是一个 Azure Keyvault 仪表板。当用户登录应用程序时,我使用 Azure Active Directory 身份验证。此应用作为 Azure 应用服务托管。

Azure Active Directory 身份验证本身工作正常,但当我尝试从 Azure 内使用 SecretClientDefaultAzureCredential 连接到 Azure Keyvault 时,它无法工作。

这是我用来收集 secret 信息的代码:

var client = new SecretClient(new Uri(this.azureKeyVaultSettings.Value.KeyVaultBaseUrl),
new DefaultAzureCredential(new DefaultAzureCredentialOptions()
{
ExcludeSharedTokenCacheCredential = false
}));

var secrets = client.GetPropertiesOfSecretsAsync();

await foreach (SecretProperties secret in secrets)
{
...
}

下面是我在 Startup.cs 中的代码。我觉得我缺少的部分是通过 oidc 登录后返回的 token 的存储,并以某种方式在 SecretClient 中利用它。我一开始以为这就是 EnableTokenAcquisitionToCallDownstreamApiAddInMemoryTokenCaches 下面所做的事情,并且 DefaultAzureCredential 会利用它,但这显然不起作用。

public void ConfigureServices(IServiceCollection services)
{
...

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(this.Configuration,
"AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(new string[]
{
"user.read"
})
.AddInMemoryTokenCaches();

services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
}).AddMicrosoftIdentityUI();

...

AppSettings.json:

{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "mydomain.com",
"TenantId": "c9db0b8f-****-****-****-************",
"ClientId": "318b64c3-****-****-****-************",
"ClientSecret": "vh27Q*********************",
"CallbackPath": "/signin-oidc"
},
"AzureKeyVaultSettings": {
"KeyVaultBaseUrl": "https://myspecialvault.vault.azure.net/"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}

我在 Azure 应用服务中遇到的错误是:

2022-03-19 11:32:49.842 +00:00 [Critical] AzureKeyVaultDashboard.Web.Controllers.HomeController: Azure.Identity.CredentialUnavailableException: DefaultAzureCredential failed to retrieve a token from the included credentials. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/defaultazurecredential/troubleshoot
- EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot- ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.- SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.- Visual Studio Token provider can't be accessed at D:\DWASFiles\Sites\myazkvdashboard\LocalAppData\.IdentityService\AzureServiceAuth\tokenprovider.json- Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot- Azure CLI not installed- PowerShell is not installed.---> System.AggregateException: Multiple exceptions were encountered while attempting to authenticate. (EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot) (ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.) (SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.) (Visual Studio Token provider can't be accessed at D:\DWASFiles\Sites\myazkvdashboard\LocalAppData\.IdentityService\AzureServiceAuth\tokenprovider.json) (Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot) (Azure CLI not installed) (PowerShell is not installed.)---> Azure.Identity.CredentialUnavailableException: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshootat Azure.Identity.CredentialDiagnosticScope.FailWrapAndThrow(Exception ex, String additionalMessage)at Azure.Identity.EnvironmentCredential.GetTokenImplAsync(Boolean async, TokenRequestContext requestContext, CancellationToken cancellationToken)at Azure.Identity.EnvironmentCredential.GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken)at Azure.Identity.DefaultAzureCredential.GetTokenFromSourcesAsync(TokenCredential[] sources, TokenRequestContext requestContext, Boolean async, CancellationToken cancellationToken)--- End of inner exception stack trace ------> (Inner Exception #1) Azure.Identity.CredentialUnavailableException: ManagedIdentityCredential authentication unavailable. Multiple attempts failed to obtain a token from the managed identity endpoint.---> System.AggregateException: Retry failed after 4 tries. Retry settings can be adjusted in ClientOptions.Retry. (An attempt was made to access a socket in a way forbidden by its access permissions. (100.100.100.100:80)) (An attempt was made to access a socket in a way forbidden by its access permissions. (100.100.100.100:80)) (An attempt was made to access a socket in a way forbidden by its access permissions. (100.100.100.100:80)) (An attempt was made to access a socket in a way forbidden by its access permissions. (100.100.100.100:80))

在本地测试时,所有这些功能似乎都工作正常。

我正在使用

  • .net 6
  • Azure.Identity - 1.5
  • Azure.Security.KeyVault.Secrets - 4.2

最佳答案

看起来好像 DefaultAzureCredential在我的情况下并没有真正起作用。我必须注入(inject) ITokenAcquisition对象进入我的构造函数并使用 ChainedCredential像这样而不是仅仅使用 DefaultAzureCredential :

var client = new SecretClient(new Uri(this.azureKeyVaultSettings.Value.KeyVaultBaseUrl),
new ChainedTokenCredential(new TokenAcquisitionTokenCredential(this.tokenAcquisition),
new DefaultAzureCredential());

var secrets = client.GetPropertiesOfSecretsAsync();

我还必须添加 https://vault.azure.net/user_impersonation.EnableTokenAcquisitionToCallDownstreamApi()称呼。请参阅下面我原来帖子中的 Startup.cs 更正:

services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(this.Configuration,
"AzureAd")
.EnableTokenAcquisitionToCallDownstreamApi(new string[]
{
"https://vault.azure.net/user_impersonation",
"user.read"
})
.AddInMemoryTokenCaches();

.EnableTokenAcquisitionToCallDownstreamApi()是什么允许 ITokenAcquisition注入(inject) Controller 中。请参阅此处了解更多详细信息:

https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-web-app-call-api-app-configuration?tabs=aspnetcore#startupcs

关于c# - Azure Active Directory 应用服务无法使用用户凭据/ token 连接到 Azure Keyvault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71538880/

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