【Azure Function】Function App代码中使用Managed Identity认证获取Blob数据时遇见400报错
问题描述
在Azure Function中,使用如下代码读取Blob内容:
try { // Retrieve the file from Azure Blob Storage BlobServiceClient bsclient = new BlobServiceClient(new Uri($"https://{SourceSA}.blob.core.chinacloudapi.cn"),new ManagedIdentityCredential(ClientID)); BlobContainerClient containerClient = bsclient.GetBlobContainerClient(ContainerName); BlobClient sourceBlobClient = containerClient.GetBlobClient($"{sourcepathWithoutContainer}"); MemoryStream SourceFileStream = new MemoryStream(); await sourceBlobClient.DownloadToAsync(SourceFileStream); SourceFileStream.Position = 0; // ... Process Logic Process ... } catch (Exception ex) { log.LogError(ex, "An error occurred while encrypting the file."); return new ObjectResult($"Error: {ex.Message}"); }
遇见了400(Bad Request)错误 ManagedIdentityCredential authentication failed: Service request failed.
在Azure Funciton所匹配的Application Insights分析页面中,发现在GET /msi/token 请求返回400。
问题解答
查看Function代码,发现ClientID参数取值是从Application Setting引用Azure Key Vault的Secret值来实现的。 而400的错误表示为客户端发起的请求URL有错误,所以怀疑是ClientID并不是正确的值。
进一步分析,在修改Key Vault Secret中的值后,Function App会缓存从Key Vault中获取的机密值,并且每24小时才会重新提取一次。
虽然文中说明重启Function App或 App Service 可以获取到新的值,但是,有时候重启应用并没有效,还需要更多的从Application Setting中修改一次才可以缓解它。
例如:KeyVault references - are returned values cached in the App Service : https://github.com/MicrosoftDocs/azure-docs/issues/36650
参考资料
- KeyVault references - are returned values cached in the App Service · Issue #36650 · MicrosoftDocs/azure-docs · GitHub
- Use Key Vault references - Azure App Service | Microsoft Learn
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2022-03-04 【Azure 应用服务】如何查看App Service Java堆栈JVM相关的参数默认配置值?
2021-03-04 【Azure 服务总线】Azure Service Bus中私信(DLQ - Dead Letter Queue)如何快速清理