如何解决.NET格式不正确的Azure Blob存储SAS令牌
我正在尝试生成一个SaS令牌,以从Azure Blob存储下载blob。生成令牌并尝试下载后,遇到以下错误:
Azure.RequestFailedException
HResult=0x80131500
Message=Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:6127b736-401e-002d-7413-aeddd5000000
Time:2020-10-29T16:53:15.3700463Z
Status: 403 (Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.)
ErrorCode: AuthenticationFailed
这是Azure中的仪表板生成的令牌:
sp=r&st=2020-10-29T16:59:18Z&se=2020-10-29T17:59:18Z&spr=https&sv=2019-12-12&sr=b&sig=KEXuzAqhUOxwvJeGAeCxJ%2BroF2D7VDnx%2BgM7ABuch%2Fs%3D
这是我生成的令牌:
sv=2019-12-12&spr=https&st=2020-10-29T16:53:51Z&se=2020-10-29T22:53:51Z&sr=b&sp=r&sig=RsVzWh/QlRtMTDUXtVVKJ3WAkCjrpr2CRXN1idEyWdc=
这是我用于生成令牌的代码:
private static Uri GetBlobSasUri(BlobContainerClient container,string blobName,StorageSharedKeyCredential key,string storedPolicyName = null)
{
// Create a SAS token that's valid for one hour.
BlobSasBuilder sasBuilder = new BlobSasBuilder()
{
BlobContainerName = container.Name,BlobName = blobName,Resource = "b",Protocol = SasProtocol.Https,};
if (storedPolicyName == null)
{
sasBuilder.StartsOn = DateTimeOffset.UtcNow;
sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(6);
sasBuilder.SetPermissions(BlobContainerSasPermissions.Read);
}
else
{
sasBuilder.Identifier = storedPolicyName;
}
// Use the key to get the SAS token.
BlobSasQueryParameters parameters = sasBuilder.ToSasQueryParameters(key);
string sasToken = Uri.UnescapeDataString(parameters.ToString());
Console.WriteLine("SAS for blob is: {0}",sasToken);
Console.WriteLine();
UriBuilder baseUri = new UriBuilder(container.GetBlockBlobClient(blobName).Uri);
baseUri.Query = sasToken;
return baseUri.Uri;
}
解决方法
我发现了问题。
- 签名需要经过UrlEncoded
- 我需要将StartsOn偏移量设置为
DateTimeOffset.UtcNow.AddMinutes(-5)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。