我正在嘗試創建一個 Web 應用程式,用戶可以在其中探索其 azure 廣告帳戶明確有權訪問的 Azure Keyvault 機密資訊。它本質上是一個 Azure Keyvault 儀表板。當用戶登錄應用程式時,我正在使用 Azure Active Directory 身份驗證。此應用程式作為 azure 應用程式服務托管。
Azure Active Directory 身份驗證本身作業正常,但是當我嘗試使用 Azure 中的SecretClientand連接到 Azure Keyvault 時DefaultAzureCredential,它無法正常作業。
這是我用來收集秘密資訊的代碼:
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 登錄后回傳的令牌并以SecretClient某種方式利用它。起初我以為這就是下面正在做的事情,EnableTokenAcquisitionToCallDownstreamApi并且會AddInMemoryTokenCaches以某種方式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();
...
應用設定.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 app 服務中遇到的錯誤是:
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
uj5u.com熱心網友回復:
似乎DefaultAzureCredential在我的情況下并沒有真正起作用。我必須將一個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注入控制器的原因。請參閱此處了解更多詳細資訊:
https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-web-app-call-api-app-configuration?tabs=aspnetcore#startupcs
uj5u.com熱心網友回復:
在部署 keyvault 和應用服務時,您可以使用應用服務的主體 ID 在 keyvault 為應用服務設定訪問策略。這樣,應用服務下托管的 Web 應用將獲得對 keyvault 的訪問權限。您可以使用 azure ad 身份驗證對登錄用戶進行身份驗證,然后在您的 Web 應用程式上提供密鑰保管庫詳細資訊。
請檢查并評論它是否適合您。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/446804.html
標籤:C# 天蓝色 天蓝色活动目录 天蓝色网络应用服务 天蓝色密钥库
