我有一個帶有密鑰保管庫的 Azure Web 應用程式。我想使用 C# 應用程式將機密存盤在密鑰保管庫中。
- 我有兩個訂閱:開發訂閱和生產訂閱。
- 每個都包含一個密鑰保管庫。
- 兩個 Key Vault 都使用“Azure 基于角色的控制”權限模型。
- 我的帳戶對兩個密鑰保管庫都具有“所有者”和“密鑰保管庫機密官”角色。
- 我可以從 Azure GUI 或 azure-cli (
az keyvault secret set)將機密上傳到這兩種環境。
我的 C# 應用程式可以將機密上傳到開發,但不能上傳到生產,無論我給它什么憑據。在生產中它總是拋出以下錯誤:
Azure.RequestFailedException: Service request failed.
Status: 403 (Forbidden)
Content:
{"error":{"code":"Forbidden","message":
"Caller is not authorized to perform action on resource.\r\n
If role assignments, deny assignments or role definitions were changed recently, please observe propagation time.\r\n
Caller: appid=<GUID>;oid=<GUID>;iss=https://sts.windows.net/<GUID>/\r\n
Action: 'Microsoft.KeyVault/vaults/secrets/setSecret/action'\r\n
Resource: '<path to my secret>'\r\n
Assignment: (not found)\r\n
Vault: <name>;location=westeurope\r\n",
"innererror":{"code":"ForbiddenByRbac"}}}
錯誤訊息說它與 RBAC 有關。我不明白它從哪里獲得它的權利。我正在從 PowerShell 提示符呼叫應用程式。我認為它會從PowerShell的拿起我的權限,但它沒有什么區別我是否做az login或az logout或az account set。無論我做什么,它都可以很好地上傳到開發中,但不能上傳到生產中。
我使用類Azure.Security.KeyVault.Secrets.SecretClient。我像這樣創建它:
private SecretClient CreateSecretClient() =>
new(
new Uri($"https://{_keyVaultName}.vault.azure.net/"),
new DefaultAzureCredential(),
new SecretClientOptions
{
Retry =
{
Delay = TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromSeconds(16),
MaxRetries = 5,
Mode = RetryMode.Exponential
}
});
我這樣寫秘密:
var keyVaultSecret = new KeyVaultSecret(secretName, value);
await _secretClient.SetSecretAsync(keyVaultSecret, ct);
我還嘗試給它一個托管身份(它應該可以訪問生產而不是開發):
new DefaultAzureCredential(
new DefaultAzureCredentialOptions
{
ManagedIdentityClientId = <GUID>
})
結果還是一樣。它愿意為開發而不是生產撰寫。我什至試圖給它一個ManagedIdentityClientId無稽之談,并沒有指向任何現有的托管身份。結果一樣。
在我看來,我似乎SecretClient忽略了其分配的憑據物件和 PowerShell 會話中的權限。它是憑空召喚出它的權限嗎?無論我做什么,它如何能夠寫入我的開發環境?我如何讓它訪問我的其他環境?
uj5u.com熱心網友回復:
我找到了一種有效的修復方法。我可以使用InteractiveBrowserCredential代替DefaultAzureCredential.
private SecretClient CreateSecretClient() =>
new(
new Uri($"https://{_keyVaultName}.vault.azure.net/"),
new InteractiveBrowserCredential(),
new SecretClientOptions
{
Retry =
{
Delay = TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromSeconds(16),
MaxRetries = 5,
Mode = RetryMode.Exponential
}
});
我也可以使用其他型別的TokenCredential,如下所列:https : //docs.microsoft.com/en-us/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348797.html
標籤:C# 天蓝色 电源外壳 azure-keyvault 红细胞
