Azure存储账户密钥轮换后,如何无需管理密钥访问Blob?
问题描述
我调用内部API获取数据,经分析处理生成电子表格后保存至Azure存储账户,随后在报表工具中创建包含Blob下载链接的记录,该链接通过StorageSharedKeyCredential和账户密钥生成。但Azure密钥轮换后这个方案就失效了,请问如何无需管理密钥即可访问Blob?
目前我使用如下函数生成Blob的SAS令牌:
private string GenerateSasToken(BlobClient blobClient) { // 定义SAS令牌参数 BlobSasBuilder sasBuilder = new BlobSasBuilder { BlobContainerName = blobClient.BlobContainerName, BlobName = blobClient.Name, Resource = "b" // "b"代表Blob,"c"代表容器 }; // 设置SAS令牌的权限和过期时间 sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write); sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddMonths(6).AddHours(1); // 使用存储账户密钥生成SAS令牌 BlobUriBuilder blobUriBuilder = new BlobUriBuilder(blobClient.Uri); StorageSharedKeyCredential storageCredentials = new StorageSharedKeyCredential(blobUriBuilder.AccountName, this.accountKey); return sasBuilder.ToSasQueryParameters(storageCredentials).ToString(); }
无需管理密钥的Blob访问方案
1. 使用Azure AD身份验证生成用户委派SAS
用户委派SAS依赖Azure AD身份,完全不需要存储账户密钥,密钥轮换不会对其产生任何影响。生成时需先获取Azure AD访问令牌,再用它签署SAS令牌。
代码示例
using Azure.Identity; using Azure.Storage.Blobs; using Azure.Storage.Sas; private async Task<string> GenerateUserDelegationSasToken(BlobClient blobClient) { // 通过DefaultAzureCredential自动获取Azure AD身份,初始化Blob服务客户端 BlobServiceClient serviceClient = new BlobServiceClient( new Uri($"https://{blobClient.AccountName}.blob.core.windows.net"), new DefaultAzureCredential()); // 获取用户委派密钥,有效期最长为7天 UserDelegationKey delegationKey = await serviceClient.GetUserDelegationKeyAsync( DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddDays(7)); // 构建SAS参数 BlobSasBuilder sasBuilder = new BlobSasBuilder { BlobContainerName = blobClient.BlobContainerName, BlobName = blobClient.Name, Resource = "b", StartsOn = DateTimeOffset.UtcNow, ExpiresOn = DateTimeOffset.UtcNow.AddMonths(6).AddHours(1) }; sasBuilder.SetPermissions(BlobSasPermissions.Read | BlobSasPermissions.Write); // 使用用户委派密钥生成SAS令牌 return sasBuilder.ToSasQueryParameters(delegationKey, blobClient.AccountName).ToString(); }
注意事项
- 运行代码的主体(如应用服务、虚拟机、本地程序)需要拥有
Storage Blob Delegator角色权限,才能获取用户委派密钥 DefaultAzureCredential会自动从环境变量、托管标识、Azure CLI等渠道获取身份,无需手动配置密钥
2. 使用托管标识直接访问Blob
如果报表工具支持Azure AD身份验证,可以直接用托管标识访问Blob,完全不需要生成SAS令牌。
实现步骤
- 给运行报表工具的服务(如Azure App Service、Power BI Premium)启用系统分配或用户分配的托管标识
- 给该托管标识分配
Storage Blob Data Reader(只读)或Storage Blob Data Contributor(读写)角色到目标存储账户/容器 - 在报表工具中配置使用托管标识连接Azure存储,直接访问Blob资源
3. 使用容器级匿名访问(仅限公开场景)
如果Blob内容是非敏感的公开数据,可以开启容器的匿名读权限,无需任何密钥或令牌就能访问。此方法安全性较低,仅适用于公开场景。
配置步骤
- 登录Azure门户,找到目标存储账户对应的容器
- 在容器的「访问策略」中设置「匿名访问级别」为「容器(匿名读取容器和Blob数据)」或「Blob(匿名读取Blob数据)」
- 设置完成后,直接使用Blob的URL即可访问,无需附加SAS令牌
内容的提问来源于stack exchange,提问作者Dakalo Nematandani
相关产品推荐
相关产品推荐

