【Azure 存储服务】代码版 Azure Storage Blob 生成 SAS (Shared Access Signature: 共享访问签名)

问题描述

在使用Azure存储服务,为了有效的保护Storage的Access Keys。可以使用另一种授权方式访问资源(Shared Access Signature: 共享访问签名), 它的好处可以控制允许访问的IP过期时间,*权限 *和 *服务 *等。Azure门户上提供了对Account级,Container级,Blob级的SAS生成服务。

No alt text provided for this image

<u style="box-sizing: border-box; text-decoration: underline;">那么使用代码如何来生成呢?</u>

问题回答

以最常见的两种代码作为示例:.NETJava

.NET

Blob SAS 将使用帐户访问密钥(Storage Account Key1 or Key2)进行签名。 使用 StorageSharedKeyCredential 类创建用于为 SAS 签名的凭据。 新建 BlobSasBuilder 对象,并调用 ToSasQueryParameters 以获取 SAS 令牌字符串。官方文档(https://docs.azure.cn/zh-cn/storage/blobs/sas-service-create?tabs=dotnet)中进行了详细介绍,直接使用以下部分代码即可生成Blob的SAS URL。

private static Uri GetServiceSasUriForBlob(BlobClient blobClient,
    string storedPolicyName = null)
{
    // Check whether this BlobClient object has been authorized with Shared Key.
    if (blobClient.CanGenerateSasUri)
    {
        // Create a SAS token that's valid for one hour.
        BlobSasBuilder sasBuilder = new BlobSasBuilder()
        {
            BlobContainerName = blobClient.GetParentBlobContainerClient().Name,
            BlobName = blobClient.Name,
            Resource = "b"
        };

        if (storedPolicyName == null)
        {
            sasBuilder.ExpiresOn = DateTimeOffset.UtcNow.AddHours(1);
            sasBuilder.SetPermissions(BlobSasPermissions.Read |
                BlobSasPermissions.Write);
        }
        else
        {
            sasBuilder.Identifier = storedPolicyName;
        }

        Uri sasUri = blobClient.GenerateSasUri(sasBuilder);
        Console.WriteLine("SAS URI for blob is: {0}", sasUri);
        Console.WriteLine();

        return sasUri;
    }
    else
    {
        Console.WriteLine(@"BlobClient must be authorized with Shared Key 
                          credentials to create a service SAS.");
        return null;
    }
}

JAVA

而Java的示例代码在官网中并没有介绍,所以本文就Java生成SAS的代码进行讲解。

从Java新版的SDK(azure-storage-blob)中 ,可以发现 BlobServiceClient,BlobContainerClient ,BlobClient 对象中都包含 generateAccountSas 或 generateSas 方法来实现对Account, Container,Blob进行SAS Token生成,只需要根据它所需要的参数对

AccountSasSignatureValues 和 BlobServiceSasSignatureValues 初始化。 示例代码(全部代码可在文末下载):

 public static void GenerateSASstring(BlobServiceClient blobServiceClient, BlobContainerClient blobContainerClient,
            BlobClient blobClient) {
        /*
         * Generate an account sas. Other samples in this file will demonstrate how to
         * create a client with the sas token.
         */
        // Configure the sas parameters. This is the minimal set.

        OffsetDateTime startTime = OffsetDateTime.now();
        OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1);
        AccountSasService services = new AccountSasService().setBlobAccess(true);
        AccountSasResourceType resourceTypes = new AccountSasResourceType().setObject(true);

        SasProtocol protocol = SasProtocol.HTTPS_ONLY;
        SasIpRange sasIpRange = SasIpRange.parse("167.220.255.73");

        // Generate the account sas.
        AccountSasPermission accountSasPermission = new AccountSasPermission().setReadPermission(true);
        AccountSasSignatureValues accountSasValues = new AccountSasSignatureValues(expiryTime, accountSasPermission,
                services, resourceTypes);
        accountSasValues.setStartTime(startTime);
        accountSasValues.setProtocol(protocol);
        accountSasValues.setSasIpRange(sasIpRange);

        String accountSasToken = blobServiceClient.generateAccountSas(accountSasValues);
        System.out.println("\nGenerate the account sas & url is :::: \n\t" + accountSasToken + "\n\t"
                + blobServiceClient.getAccountUrl() + "?" + accountSasToken);

        // Generate a sas using a container client
        BlobContainerSasPermission containerSasPermission = new BlobContainerSasPermission().setCreatePermission(true);
        BlobServiceSasSignatureValues serviceSasValues = new BlobServiceSasSignatureValues(expiryTime,
                containerSasPermission);
        serviceSasValues.setStartTime(startTime);
        serviceSasValues.setProtocol(protocol);
        serviceSasValues.setSasIpRange(sasIpRange);

        String containerSasToken = blobContainerClient.generateSas(serviceSasValues);
        System.out.println("\nGenerate the Container sas & url is :::: \n\t" + containerSasToken + "\n\t"
                + blobContainerClient.getBlobContainerUrl() + "?" + containerSasToken);

        // Generate a sas using a blob client
        BlobSasPermission blobSasPermission = new BlobSasPermission().setReadPermission(true);
        serviceSasValues = new BlobServiceSasSignatureValues(expiryTime, blobSasPermission);
        serviceSasValues.setStartTime(startTime);
        serviceSasValues.setProtocol(protocol);
        serviceSasValues.setSasIpRange(sasIpRange);

        String blobSasToken = blobClient.generateSas(serviceSasValues);
        System.out.println("\nGenerate the Blob sas & url is :::: \n\t" + blobSasToken + "\n\t"
                + blobClient.getBlobUrl() + "?" + blobSasToken);

    }

在pom.xml 中所需要加载的依赖项:

    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-storage-blob</artifactId>
      <version>12.13.0</version>
    </dependency>

以上代码中的各部分设置项 与 Azure门户上设置项的对应关系如下图:


No alt text provided for this image

运行效果图

No alt text provided for this image

附录一:Java Main函数全部代码:

package test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.time.OffsetDateTime;
import java.util.Iterator;

import com.azure.storage.blob.BlobClient;
import com.azure.storage.blob.BlobContainerClient;
import com.azure.storage.blob.BlobServiceClient;
import com.azure.storage.blob.BlobServiceClientBuilder;
import com.azure.storage.blob.models.BlobItem;
import com.azure.storage.blob.sas.BlobContainerSasPermission;
import com.azure.storage.blob.sas.BlobSasPermission;
import com.azure.storage.blob.sas.BlobServiceSasSignatureValues;
import com.azure.storage.common.sas.AccountSasPermission;
import com.azure.storage.common.sas.AccountSasResourceType;
import com.azure.storage.common.sas.AccountSasService;
import com.azure.storage.common.sas.AccountSasSignatureValues;
import com.azure.storage.common.sas.SasIpRange;
import com.azure.storage.common.sas.SasProtocol;

/**
 * Hello world!
 *
 */
public class App {
    public static void main(String[] args)
            throws URISyntaxException, InvalidKeyException, RuntimeException, IOException {
        System.out.println("Hello World!");

        String storageConnectionString = "DefaultEndpointsProtocol=https;AccountName=<your storage account name>;AccountKey=**************************;EndpointSuffix=core.chinacloudapi.cn";
        String blobContainerName = "test";
        String dirName = "";

        // Create a BlobServiceClient object which will be used to create a container
        System.out.println("\nCreate a BlobServiceClient Object to Connect Storage Account");
        BlobServiceClient blobServiceClient = new BlobServiceClientBuilder().connectionString(storageConnectionString)
                .buildClient();

        // Create a unique name for the container
        String containerName = blobContainerName + java.util.UUID.randomUUID();

        // Create the container and return a container client object
        System.out.println("\nCreate new Container : " + containerName);
        BlobContainerClient containerClient = blobServiceClient.createBlobContainer(containerName);

        // Create a local file in the ./data/ directory for uploading and downloading

        System.out.println("\nCreate a local file in the ./data/ directory for uploading and downloading");
        String localPath = "./data/";
        String fileName = "quickstart" + java.util.UUID.randomUUID() + ".txt";
        File localFile = new File(localPath + fileName);
        // Write text to the file
        FileWriter writer = new FileWriter(localPath + fileName, true);
        writer.write("Hello, World! This is test file to download by SAS. Also test upload");
        writer.close();

        // Get a reference to a blob
        BlobClient blobClient = containerClient.getBlobClient(fileName);
        System.out.println("\nUploading to Blob storage as blob:\n\t" + blobClient.getBlobUrl());
        // Upload the blob
        blobClient.uploadFromFile(localPath + fileName);
        System.out.println("\nUpload blob completed : " + blobClient.getBlobName());

        System.out.println("\nListing blobs...");

        // List the blob(s) in the container.
        for (BlobItem blobItem : containerClient.listBlobs()) {
            System.out.println("\t" + blobItem.getName());
        }

        // Download the blob to a local file
        // Append the string "DOWNLOAD" before the .txt extension so that you can see
        // both files.
        String downloadFileName = fileName.replace(".txt", "DOWNLOAD.txt");
        File downloadedFile = new File(localPath + downloadFileName);

        System.out.println("\nDownloading blob to\n\t " + localPath + downloadFileName);

        blobClient.downloadToFile(localPath + downloadFileName);

        // Generate SAS String for blob user..
        System.out.println("\nGenerate SAS String for blob user..");
        GenerateSASstring(blobServiceClient, containerClient, blobClient);

        // Clean up
        System.out.println("\nPress the Enter word 'Delete' to begin clean up");
        boolean isDelete = System.console().readLine().toLowerCase().trim().equals("delete");

        if (isDelete) {
            System.out.println("Deleting blob container...");
            containerClient.delete();

            System.out.println("Deleting the local source and downloaded files...");
            localFile.delete();
            downloadedFile.delete();
        } else {
            System.out.println("Skip to Clean up operation");
        }

        System.out.println("Done");

    }

    public static void GenerateSASstring(BlobServiceClient blobServiceClient, BlobContainerClient blobContainerClient,
            BlobClient blobClient) {
        /*
         * Generate an account sas. Other samples in this file will demonstrate how to
         * create a client with the sas token.
         */
        // Configure the sas parameters. This is the minimal set.

        OffsetDateTime startTime = OffsetDateTime.now();
        OffsetDateTime expiryTime = OffsetDateTime.now().plusDays(1);
        AccountSasService services = new AccountSasService().setBlobAccess(true);
        AccountSasResourceType resourceTypes = new AccountSasResourceType().setObject(true);

        SasProtocol protocol = SasProtocol.HTTPS_ONLY;
        SasIpRange sasIpRange = SasIpRange.parse("167.220.255.73");

        // Generate the account sas.
        AccountSasPermission accountSasPermission = new AccountSasPermission().setReadPermission(true);
        AccountSasSignatureValues accountSasValues = new AccountSasSignatureValues(expiryTime, accountSasPermission,
                services, resourceTypes);
        accountSasValues.setStartTime(startTime);
        accountSasValues.setProtocol(protocol);
        accountSasValues.setSasIpRange(sasIpRange);

        String accountSasToken = blobServiceClient.generateAccountSas(accountSasValues);
        System.out.println("\nGenerate the account sas & url is :::: \n\t" + accountSasToken + "\n\t"
                + blobServiceClient.getAccountUrl() + "?" + accountSasToken);

        // Generate a sas using a container client
        BlobContainerSasPermission containerSasPermission = new BlobContainerSasPermission().setCreatePermission(true);
        BlobServiceSasSignatureValues serviceSasValues = new BlobServiceSasSignatureValues(expiryTime,
                containerSasPermission);
        serviceSasValues.setStartTime(startTime);
        serviceSasValues.setProtocol(protocol);
        serviceSasValues.setSasIpRange(sasIpRange);

        String containerSasToken = blobContainerClient.generateSas(serviceSasValues);
        System.out.println("\nGenerate the Container sas & url is :::: \n\t" + containerSasToken + "\n\t"
                + blobContainerClient.getBlobContainerUrl() + "?" + containerSasToken);

        // Generate a sas using a blob client
        BlobSasPermission blobSasPermission = new BlobSasPermission().setReadPermission(true);
        serviceSasValues = new BlobServiceSasSignatureValues(expiryTime, blobSasPermission);
        serviceSasValues.setStartTime(startTime);
        serviceSasValues.setProtocol(protocol);
        serviceSasValues.setSasIpRange(sasIpRange);

        String blobSasToken = blobClient.generateSas(serviceSasValues);
        System.out.println("\nGenerate the Blob sas & url is :::: \n\t" + blobSasToken + "\n\t"
                + blobClient.getBlobUrl() + "?" + blobSasToken);

    }

}

参考资料

快速入门:使用 Java v12 SDK 管理 blob:https://docs.azure.cn/zh-cn/storage/blobs/storage-quickstart-blobs-java

Azure Storage Blob client library for Java:https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/storage/azure-storage-blob#generate-a-sas-token

示例下载:demo.rar

当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!

分类: 【Azure 存储服务】

标签: Shared Access Signature: 共享访问签名, JAVA 生成SAS, Azure Storage, Azure Developer

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,386评论 6 479
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,939评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,851评论 0 341
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,953评论 1 278
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,971评论 5 369
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,784评论 1 283
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,126评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,765评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,148评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,744评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,858评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,479评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,080评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,053评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,278评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,245评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,590评论 2 343

推荐阅读更多精彩内容