【问题标题】:How to create Azure Storage SAS token using DefaultAzureCredential class如何使用 DefaultAzureCredential 类创建 Azure 存储 SAS 令牌
【发布时间】:2022-07-19 11:47:29
【问题描述】:

我想创建 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)

【问题讨论】:

    标签: azure go azure-blob-storage azure-storage azure-sdk-for-go


    【解决方案1】:

    如何使用托管标识生成 sas 令牌?

    您可以通过使用DefaultAzureCredential 和正确的access 来生成它到存储容器中的那个blob。

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

    示例代码:

        var strgAccName = _configuration.GetValue<string>("YourStorageAccountName");
        var saUri = $"https://{strgAccName}.blob.core.windows.net";
        var blobServiceClient = new BlobServiceClient(new Uri(saUri), new DefaultAzureCredential());
        var blobContainerClient = blobServiceClient.GetBlobContainerClient(_configuration.GetValue<string>("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,请参阅此以了解分步过程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      • 2020-03-08
      • 1970-01-01
      • 2020-05-30
      • 1970-01-01
      • 2022-06-13
      • 2019-12-05
      相关资源
      最近更新 更多