You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell生成符合特定条件的DataLake目录SAS Token

解决方法:用PowerShell生成基于空访问策略的自定义SAS Token

由于Az模块的New-AzStorageBlobSASToken存在参数集限制,无法同时指定访问策略和自定义权限/时间参数,你可以直接使用Azure.Storage.Blobs .NET库来实现和Azure门户一致的SAS生成逻辑。以下是具体步骤和代码:

步骤说明

  1. 利用Azure.Storage.Blobs的BlobContainerClient和BlobSasBuilder,可以灵活组合访问策略名称、自定义权限及起止时间
  2. 虚拟目录本质是Blob存储的前缀,因此需要生成容器级SAS并指定目录前缀,确保仅允许访问目标目录

完整PowerShell代码

# 配置参数
$storageAccountName = "gfcssa002t"
$resourceGroupName = "<你的资源组名称>" # 替换为实际资源组名
$containerName = "datalake"
$directoryPrefix = "basefolder/testfolder/" # 末尾加斜杠匹配目录下所有内容
$policyName = "testpolicy"
$startTime = (Get-Date).AddMinutes(-5) # 提前5分钟避免客户端与服务器时间偏差
$expiryTime = (Get-Date).AddHours(24) # 替换为实际过期时间

# 获取存储账户密钥
$storageKey = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value[0]

# 初始化Container客户端
$containerUri = "https://$storageAccountName.blob.core.windows.net/$containerName"
$sharedKeyCredential = [Azure.Storage.StorageSharedKeyCredential]::new($storageAccountName, $storageKey)
$containerClient = [Azure.Storage.Blobs.BlobContainerClient]::new($containerUri, $sharedKeyCredential)

# 构造SAS参数
$sasBuilder = [Azure.Storage.Sas.BlobSasBuilder]::new()
$sasBuilder.Protocol = [Azure.Storage.Sas.SasProtocol]::HttpsOnly # 仅允许HTTPS访问
$sasBuilder.StartTime = $startTime
$sasBuilder.ExpiryTime = $expiryTime
# 指定所需权限:Read、Add、Create、Write、List
$sasBuilder.Permissions = [Azure.Storage.Sas.BlobContainerSasPermissions]::Read -bor `
                          [Azure.Storage.Sas.BlobContainerSasPermissions]::Add -bor `
                          [Azure.Storage.Sas.BlobContainerSasPermissions]::Create -bor `
                          [Azure.Storage.Sas.BlobContainerSasPermissions]::Write -bor `
                          [Azure.Storage.Sas.BlobContainerSasPermissions]::List
$sasBuilder.Resource = "c" # 标识为容器级SAS
$sasBuilder.Prefix = $directoryPrefix # 限制访问指定目录
$sasBuilder.Identifier = $policyName # 关联已创建的空访问策略

# 生成SAS Token
$sasToken = $containerClient.GenerateSasUri($sasBuilder).Query

# 输出结果
Write-Host "生成的SAS Token:"
Write-Output $sasToken

关键说明

  • 代码中使用BlobContainerSasPermissions枚举组合权限,避免手动输入权限缩写出错
  • 指定Resource = "c"表示容器级SAS,配合Prefix参数精准控制目录访问范围
  • 通过Identifier参数关联空访问策略,实现与Azure门户完全一致的签名逻辑
  • 提前设置StartTime是为了避免客户端与Azure服务器的时间同步问题

内容的提问来源于stack exchange,提问作者Andreas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:05:22