登录
首页 >  Golang >  Go问答

使用 DefaultAzureCredential 类生成 Azure 存储 SAS 令牌

来源:stackoverflow

时间:2024-02-26 11:48:27 479浏览 收藏

一分耕耘,一分收获!既然都打开这篇《使用 DefaultAzureCredential 类生成 Azure 存储 SAS 令牌》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

我想创建 sas 令牌来下载存储在 azure 存储中的容器中的 blob。我可以使用共享凭证轻松生成 sas 令牌,但这需要存储访问密钥。如何使用托管身份生成 sas 令牌。

credential, err := azblob.NewSharedKeyCredential(accountName, accountKey)
        sasQueryParams, err := azblob.BlobSASSignatureValues{
            Protocol:      azblob.SASProtocolHTTPS,
            ExpiryTime:    time.Now().UTC().Add(4 * time.Hour),
            ContainerName: containerName,
            BlobName:      blobName,
            Permissions:   azblob.BlobSASPermissions{Add: false, 
    Read: true, Write: false}.String(),
    }.NewSASQueryParameters(credential)

正确答案


您可以通过使用 defaultazurecredential 和存储容器中该 blob 的正确 access 来生成它。

使用默认 azure 凭据类的 azure ad 凭据连接到存储帐户。

示例代码:

    var strgAccName = _configuration.GetValue("YourStorageAccountName");
    var saUri = $"https://{strgAccName}.blob.core.windows.net";
    var blobServiceClient = new BlobServiceClient(new Uri(saUri), new DefaultAzureCredential());
    var blobContainerClient = blobServiceClient.GetBlobContainerClient(_configuration.GetValue("YourContainerName"));
    var blobClient = blobContainerClient.GetBlobClient("YourImage.jpg"); 
    // We can issue the SAS token till a maximum of 7 days.
    var userDelegationKey =  blobServiceClient.GetUserDelegationKey(DateTimeOffset.UtcNow,
                                                                    DateTimeOffset.UtcNow.AddHours(4)); 
                                                            
    var sasBuilder = new BlobSasBuilder()
    {
        BlobContainerName = blobClient.BlobContainerName,
        BlobName = blobClient.Name,
        Resource = "b", // b: blob, c: container
        StartsOn = DateTimeOffset.UtcNow,
        ExpiresOn = DateTimeOffset.UtcNow.AddHours(4),
    };

    sasBuilder.SetPermissions(BlobSasPermissions.Read); 
    var blobUriBuilder = new BlobUriBuilder(blobClient.Uri)
    {
        Sas = sasBuilder.ToSasQueryParameters(userDelegationKey,blobServiceClient.AccountName)
    };
    // Read this in any view like `blobUriBuilder.ToUri().ToString();`
}

并重新检查该 blob 是否存在委派访问权限。 因此,我们不为此使用任何访问密钥和连接字符串。

感谢 @anupam maiti 提供此 Article,请参阅此了解分步过程。

以上就是《使用 DefaultAzureCredential 类生成 Azure 存储 SAS 令牌》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>