【Azure 存儲服務(wù)】代碼版 Azure Storage Blob 生成 SAS (Shared Access Signature: 共享訪問簽名)

問題描述

在使用Azure存儲服務(wù)汗侵,為了有效的保護Storage的Access Keys迫像〉睹疲可以使用另一種授權(quán)方式訪問資源(Shared Access Signature: 共享訪問簽名), 它的好處可以控制允許訪問的IP遇八,過期時間敞恋,*權(quán)限 *和 *服務(wù) *等。Azure門戶上提供了對Account級瘤泪,Container級灶泵,Blob級的SAS生成服務(wù)。

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 類創(chuàng)建用于為 SAS 簽名的憑據(jù)。 新建 BlobSasBuilder 對象实檀,并調(diào)用 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的示例代碼在官網(wǎng)中并沒有介紹恬吕,所以本文就Java生成SAS的代碼進行講解签则。

從Java新版的SDK(azure-storage-blob)中 ,可以發(fā)現(xiàn) BlobServiceClient铐料,BlobContainerClient 渐裂,BlobClient 對象中都包含 generateAccountSas 或 generateSas 方法來實現(xiàn)對Account, Container钠惩,Blob進行SAS Token生成柒凉,只需要根據(jù)它所需要的參數(shù)對

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>

以上代碼中的各部分設(shè)置項 與 Azure門戶上設(shè)置項的對應(yīng)關(guān)系如下圖:


No alt text provided for this image

運行效果圖

No alt text provided for this image

附錄一:Java Main函數(shù)全部代碼:

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

當(dāng)在復(fù)雜的環(huán)境中面臨問題篓跛,格物之道需:濁而靜之徐清膝捞,安以動之徐生。 云中愧沟,恰是如此!

分類: 【Azure 存儲服務(wù)】

標(biāo)簽: Shared Access Signature: 共享訪問簽名, JAVA 生成SAS, Azure Storage, Azure Developer

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蔬咬,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子央渣,更是在濱河造成了極大的恐慌计盒,老刑警劉巖渴频,帶你破解...
    沈念sama閱讀 219,589評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件芽丹,死亡現(xiàn)場離奇詭異,居然都是意外死亡卜朗,警方通過查閱死者的電腦和手機拔第,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,615評論 3 396
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來场钉,“玉大人蚊俺,你說我怎么就攤上這事」渫颍” “怎么了泳猬?”我有些...
    開封第一講書人閱讀 165,933評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長宇植。 經(jīng)常有香客問我得封,道長,這世上最難降的妖魔是什么指郁? 我笑而不...
    開封第一講書人閱讀 58,976評論 1 295
  • 正文 為了忘掉前任忙上,我火速辦了婚禮,結(jié)果婚禮上闲坎,老公的妹妹穿的比我還像新娘疫粥。我一直安慰自己茬斧,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,999評論 6 393
  • 文/花漫 我一把揭開白布梗逮。 她就那樣靜靜地躺著项秉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪库糠。 梳的紋絲不亂的頭發(fā)上伙狐,一...
    開封第一講書人閱讀 51,775評論 1 307
  • 那天,我揣著相機與錄音瞬欧,去河邊找鬼贷屎。 笑死,一個胖子當(dāng)著我的面吹牛艘虎,可吹牛的內(nèi)容都是我干的唉侄。 我是一名探鬼主播,決...
    沈念sama閱讀 40,474評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼野建,長吁一口氣:“原來是場噩夢啊……” “哼属划!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起候生,我...
    開封第一講書人閱讀 39,359評論 0 276
  • 序言:老撾萬榮一對情侶失蹤同眯,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后唯鸭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體须蜗,經(jīng)...
    沈念sama閱讀 45,854評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,007評論 3 338
  • 正文 我和宋清朗相戀三年目溉,在試婚紗的時候發(fā)現(xiàn)自己被綠了明肮。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,146評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡缭付,死狀恐怖柿估,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情陷猫,我是刑警寧澤秫舌,帶...
    沈念sama閱讀 35,826評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站绣檬,受9級特大地震影響足陨,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜河咽,卻給世界環(huán)境...
    茶點故事閱讀 41,484評論 3 331
  • 文/蒙蒙 一钠右、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧忘蟹,春花似錦飒房、人聲如沸搁凸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,029評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽护糖。三九已至,卻和暖如春嚼松,著一層夾襖步出監(jiān)牢的瞬間嫡良,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,153評論 1 272
  • 我被黑心中介騙來泰國打工献酗, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留寝受,地道東北人。 一個月前我還...
    沈念sama閱讀 48,420評論 3 373
  • 正文 我出身青樓罕偎,卻偏偏與公主長得像很澄,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子颜及,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,107評論 2 356

推薦閱讀更多精彩內(nèi)容