使用共用存取簽章 (SAS)Using shared access signatures (SAS)

若要在無須提供您帳戶金鑰的情況下,將儲存體帳戶中物件的限制存取授與其他用戶端,則可使用共用存取簽章 (SAS) 達成此目標。A shared access signature (SAS) provides you with a way to grant limited access to objects in your storage account to other clients, without exposing your account key. 本文會提供有關 SAS 模型的概觀、檢閱最佳做法以及查看一些範例。In this article, we provide an overview of the SAS model, review SAS best practices, and look at some examples.

除了本文所提供的範例外,如果您還需要其他使用 SAS 的程式碼範例,請參閱在 .NET 中開始使用 Azure Blob 儲存體Azure 程式碼範例程式庫提供的其他範例。For additional code examples using SAS beyond those presented here, see Getting Started with Azure Blob Storage in .NET and other samples available in the Azure Code Samples library. 您可以下載範例應用程式並加以執行,或瀏覽 GitHub 上的程式碼。You can download the sample applications and run them, or browse the code on GitHub.

共用存取簽章為何?What is a shared access signature?

共用存取簽章可提供您儲存體帳戶中資源的委派存取。A shared access signature provides delegated access to resources in your storage account. 透過 SAS,您可以對用戶端授與儲存體帳戶中資源的存取權,而不必共用帳戶金鑰。With a SAS, you can grant clients access to resources in your storage account, without sharing your account keys. 這是在您應用程式中使用共用存取簽章的重點 - SAS 是共用儲存體資源的安全方式,而不會危害您的帳戶金鑰。This is the key point of using shared access signatures in your applications--a SAS is a secure way to share your storage resources without compromising your account keys.

重要

儲存體帳戶金鑰很類似儲存體帳戶的根密碼。Your storage account key is similar to the root password for your storage account. 請務必小心保護您的帳戶金鑰。Always be careful to protect your account key. 請避免轉發給其他使用者、進行硬式編碼,或將它儲存在其他人可以存取的純文字當中。Avoid distributing it to other users, hard-coding it, or saving it anywhere in plaintext that is accessible to others. 如果您認為帳戶金鑰可能遭到破解,請使用 Azure 入口網站重新產生帳戶金鑰。Regenerate your account key using the Azure portal if you believe it may have been compromised.

SAS (共用存取簽章) 權杖就像帳戶存取金鑰一樣,非常需要受到保護。SAS (Shared Access Signature) tokens are critical to protect just like the account access keys. 提供細微性時,SAS 會為用戶端授與存取儲存體帳戶中資源的權限,而且不應該公開共用。While providing granularity SAS grants clients access to the resources in your storage account and should not be shared publicly. 若基於疑難排解因素而需要共用,請考慮使用任意記錄檔的編校版本,或從記錄檔中刪除 SAS 權杖 (如果有的話),並確定螢幕擷取畫面也不會包含 SAS 資訊。When sharing is required for troubleshooting reasons consider using a redacted version of any log files or deleting the SAS tokens (if present) from the log files, and make sure the screenshots don't contain the SAS information either.

Microsoft 建議使用 Azure Active Directory (Azure AD) 驗證 Blob 和佇列儲存體應用程式 (預覽),藉以盡可能增強安全性。Microsoft recommends using Azure Active Directory (Azure AD) authentication for your Blob and Queue storage applications (preview) when possible for enhanced security. 如需詳細資訊,請參閱使用 Azure Active Directory 來驗證 Azure Blob 和佇列的存取權 (預覽)For more information, see Authenticate access to Azure blobs and queues using Azure Active Directory (preview).

SAS 可讓您更細微地控制要對擁有 SAS 的用戶端授與何種類型的存取權,包括︰A SAS gives you granular control over the type of access you grant to clients who have the SAS, including:

  • SAS 的有效期間,包括開始時間和到期時間。The interval over which the SAS is valid, including the start time and the expiry time.
  • SAS 所授與的權限。The permissions granted by the SAS. 例如,Blob 的 SAS 可能會授與該 Blob 的讀取和寫入權限,但不授與刪除權限。For example, a SAS for a blob might grant read and write permissions to that blob, but not delete permissions.
  • Azure 儲存體接受的 SAS 所來自的選擇性 IP 位址或 IP 位址範圍。An optional IP address or range of IP addresses from which Azure Storage will accept the SAS. 例如,您可以指定屬於組織的 IP 位址範圍。For example, you might specify a range of IP addresses belonging to your organization.
  • Azure 儲存體接受的 SAS 所透過的通訊協定。The protocol over which Azure Storage will accept the SAS. 您可以使用這個選擇性參數來限制使用 HTTPS 之用戶端的存取權。You can use this optional parameter to restrict access to clients using HTTPS.

使用共用存取簽章的時機?When should you use a shared access signature?

當您想要將儲存體帳戶中的資源存取權提供給未具有您儲存體帳戶存取金鑰的用戶端時,即可使用 SAS。You can use a SAS when you want to provide access to resources in your storage account to any client not possessing your storage account's access keys. 您的儲存體帳戶包含主要與次要存取金鑰,兩者皆可授與帳戶及帳戶內所有資源的系統管理存取權。Your storage account includes both a primary and secondary access key, both of which grant administrative access to your account, and all resources within it. 提供以上任一金鑰,皆有可能讓您的帳戶遭到惡意或粗心使用。Exposing either of these keys opens your account to the possibility of malicious or negligent use. 共用存取簽章提供了安全的替代方式,無需帳戶金鑰便可讓用戶端根據獲明確授與的權限,來讀取、寫入及刪除您儲存體帳戶中的資料。Shared access signatures provide a safe alternative that allows clients to read, write, and delete data in your storage account according to the permissions you've explicitly granted, and without need for an account key.

證明 SAS 非常有用的一個常見案例,就是使用者在您的儲存體帳戶中讀取和寫入自己的資料。A common scenario where a SAS is useful is a service where users read and write their own data to your storage account. 在儲存體帳戶儲存使用者資料的案例中,典型的設計模式有兩種:In a scenario where a storage account stores user data, there are two typical design patterns:

  1. 用戶端通過前端 Proxy 服務 (執行驗證) 來上傳與下載資料。Clients upload and download data via a front-end proxy service, which performs authentication. 此前端 Proxy 服務有個好處,那就是允許商務規則的驗證,但在大量資料或大量交易的情況下,建立可調整以符合需求的服務可能十分昂貴或困難。This front-end proxy service has the advantage of allowing validation of business rules, but for large amounts of data or high-volume transactions, creating a service that can scale to match demand may be expensive or difficult.

    案例圖表:前端 Proxy 服務

  2. 輕量型服務可視需要驗證用戶端,然後產生 SAS。A lightweight service authenticates the client as needed and then generates a SAS. 在用戶端收到 SAS 之後,他們可以使用 SAS 所定義的權限,並在 SAS 允許的間隔內直接存取儲存體帳戶資源。Once the client receives the SAS, they can access storage account resources directly with the permissions defined by the SAS and for the interval allowed by the SAS. SAS 可減輕透過前端 Proxy 服務路由所有資料的需求。The SAS mitigates the need for routing all data through the front-end proxy service.

    案例圖表:SAS 提供者服務

許多實際服務可能會混合運用這兩種方法。Many real-world services may use a hybrid of these two approaches. 例如,某些資料可能會透過前端 Proxy 處理和驗證,其他資料則會直接使用 SAS 來儲存和/或讀取。For example, some data might be processed and validated via the front-end proxy, while other data is saved and/or read directly using SAS.

此外,在某些情況下,您必須使用 SAS 來授權存取複製作業中的來源物件:Additionally, you will need to use a SAS to authorize access to the source object in a copy operation in certain scenarios:

  • 當您將 Blob 複製到另一個位於不同儲存體帳戶的 Blob 時,必須使用 SAS 來授權存取來源 Blob。When you copy a blob to another blob that resides in a different storage account, you must use a SAS to authorize access to the source blob. 您也可以選擇性地使用 SAS 來授權存取目的地 Blob。You can optionally use a SAS to authorize access to the destination blob as well.
  • 當您將檔案複製到另一個位於不同儲存體帳戶的檔案時,必須使用 SAS 來授權存取來源檔案。When you copy a file to another file that resides in a different storage account, you must use a SAS to authorize access to the source file. 您也可以選擇性地使用 SAS 來授權存取目的檔案。You can optionally use a SAS to authorize access to the destination file as well.
  • 當您將 Blob 複製到檔案,或將檔案複製到 Blob 時,必須使用 SAS 來授權存取來源物件,即使來源和目的地物件位於相同的儲存體帳戶內也一樣。When you copy a blob to a file, or a file to a blob, you must use a SAS to authorize access to the source object, even if the source and destination objects reside within the same storage account.

共用存取簽章的類型Types of shared access signatures

您可建立兩種類型的共用存取簽章:You can create two types of shared access signatures:

  • 服務 SAS。Service SAS. 服務 SAS 只會將存取權限委派給一種儲存體服務資源:Blob、佇列、資料表或檔案服務。The service SAS delegates access to a resource in just one of the storage services: the Blob, Queue, Table, or File service. 如需有關建構服務 SAS 權杖的深入資訊,請參閱建構服務 SAS服務 SAS 範例See Constructing a Service SAS and Service SAS Examples for in-depth information about constructing the service SAS token.
  • 帳戶 SAS。Account SAS. 帳戶 SAS 則將存取權限委派給一或多個儲存體服務的資源。The account SAS delegates access to resources in one or more of the storage services. 可透過服務 SAS 取得的所有作業也可透過帳戶 SAS 取得。All of the operations available via a service SAS are also available via an account SAS. 此外,利用帳戶 SAS,您可以委派適用指定的服務作業 (例如:取得/設定服務屬性取得服務統計資料) 的存取。您也可以將 Blob 容器、資料表、佇列和檔案共用的讀取、寫入和刪除作業的存取權限,委派給本無權限的服務 SAS。Additionally, with the account SAS, you can delegate access to operations that apply to a given service, such as Get/Set Service Properties and Get Service Stats. You can also delegate access to read, write, and delete operations on blob containers, tables, queues, and file shares that are not permitted with a service SAS. 如需有關建構帳戶 SAS 權杖的深入資訊,請參閱建構帳戶 SASSee Constructing an Account SAS for in-depth information about constructing the account SAS token.

共用存取簽章的運作方式How a shared access signature works

共用存取簽章是指向一或多個儲存體資源,並包括含有一組特殊的查詢參數權杖的已簽署 URI。A shared access signature is a signed URI that points to one or more storage resources and includes a token that contains a special set of query parameters. 權杖指出用戶端可以如何存取資源。The token indicates how the resources may be accessed by the client. 簽章是查詢參數的其中一個,根據 SAS 參數所建構並使用帳戶金鑰進行簽署。One of the query parameters, the signature, is constructed from the SAS parameters and signed with the account key. Azure 儲存體會使用此簽章來授權存取儲存體資源。This signature is used by Azure Storage to authorize access to the storage resource.

以下是 SAS URI 範例,其顯示資源 URI 和 SAS 權杖︰Here's an example of a SAS URI, showing the resource URI and the SAS token:

SAS URI 的元件

SAS 權杖是用戶端所產生的字串 (如需程式碼範例,請參閱〈SAS 範例〉一節)。The SAS token is a string you generate on the client side (see the SAS examples section for code examples). 譬如 Azure 儲存體不會以任何方式,追蹤您透過儲存體用戶端程式庫所產生的 SAS 權杖。A SAS token you generate with the storage client library, for example, is not tracked by Azure Storage in any way. 您可以在用戶端建立不限數量的 SAS 權杖。You can create an unlimited number of SAS tokens on the client side.

當用戶端在要求中提供 SAS URI 給 Azure 儲存體時,服務會檢查 SAS 參數和簽章,以確認它是有效的,可用於驗證要求。When a client provides a SAS URI to Azure Storage as part of a request, the service checks the SAS parameters and signature to verify that it is valid for authenticating the request. 如果服務確認簽章有效,則要求會獲得授權。If the service verifies that the signature is valid, then the request is authorized. 否則要求會遭到拒絕,並產生錯誤碼 403 (禁止)。Otherwise, the request is declined with error code 403 (Forbidden).

共用存取簽章參數Shared access signature parameters

帳戶 SAS 和服務 SAS 權杖包含一些常見的參數,並且採取幾個不同參數。The account SAS and service SAS tokens include some common parameters, and also take a few parameters that are different.

帳戶 SAS 和服務 SAS 權杖的通用參數Parameters common to account SAS and service SAS tokens

  • API 版本 選擇性參數,指定要用來執行要求的儲存體服務版本。Api version An optional parameter that specifies the storage service version to use to execute the request.
  • 服務版本 必要參數,指定要用來授權要求的儲存體服務版本。Service version A required parameter that specifies the storage service version to use to authorize the request.
  • 開始時間。Start time. 這是指 SAS 生效的時間。This is the time at which the SAS becomes valid. 共用存取簽章的開始時間為選擇性。The start time for a shared access signature is optional. 若省略開始時間,SAS 便會立即生效。If a start time is omitted, the SAS is effective immediately. 開始時間必須以 UTC (國際標準時間) 表示,並包含特殊的 UTC 指示項 ("Z"),例如 1994-11-05T13:15:30ZThe start time must be expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"), for example 1994-11-05T13:15:30Z.
  • 到期時間。Expiry time. 這是指 SAS 何時失效的時間。This is the time after which the SAS is no longer valid. 最佳做法建議您為 SAS 指定過期時間,或將它與預存存取原則建立關聯。Best practices recommend that you either specify an expiry time for a SAS, or associate it with a stored access policy. 過期時間必須以 UTC (國際標準時間) 表示,並包含特殊的 UTC 指示項 ("Z"),例如 1994-11-05T13:15:30Z (參閱以下的更多資訊)。The expiry time must be expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"), for example 1994-11-05T13:15:30Z (see more below).
  • 權限。Permissions. 在 SAS 上指定的權限表示用戶端可以使用 SAS 來對儲存體資源執行哪些作業。The permissions specified on the SAS indicate what operations the client can perform against the storage resource using the SAS. 帳戶 SAS 和服務 SAS 的可用權限不同。Available permissions differ for an account SAS and a service SAS.
  • IP。IP. 選用參數,可指定要從中接受要求且位於 Azure 外部的 IP 位址或 IP 位址範圍 (請參閱適用於 Express Route 的 路由工作階段組態狀態 一節)。An optional parameter that specifies an IP address or a range of IP addresses outside of Azure (see the section Routing session configuration state for Express Route) from which to accept requests.
  • 通訊協定。Protocol. 選擇性參數,指定對要求允許的通訊協定。An optional parameter that specifies the protocol permitted for a request. 可能的值為 HTTPS 和 HTTP (https,http),其為預設值或僅限 HTTPS (https)。Possible values are both HTTPS and HTTP (https,http), which is the default value, or HTTPS only (https). 請注意,僅 HTTP 是不允許的值。Note that HTTP only is not a permitted value.
  • 簽章。Signature. 簽章是從其他參數建構,指定為權杖的一部分,然後加密。The signature is constructed from the other parameters specified as part token and then encrypted. 此簽章會用來授權存取指定的儲存體資源。The signature is used to authorize access to the specified storage resources.

服務 SAS 權杖的參數Parameters for a service SAS token

  • 儲存體資源。Storage resource. 可以委派對服務 SAS 存取的儲存體資源包括:Storage resources for which you can delegate access with a service SAS include:
    • 容器和 BlobContainers and blobs
    • 檔案共用及檔案File shares and files
    • 佇列Queues
    • 資料表和資料表實體範圍。Tables and ranges of table entities.

帳戶 SAS 權杖的參數Parameters for an account SAS token

  • 一或多個服務。Service or services. 帳戶 SAS 可以委派存取給一或多個儲存體服務。An account SAS can delegate access to one or more of the storage services. 例如,您可以建立委派存取 Blob 和檔案服務的帳戶 SAS。For example, you can create an account SAS that delegates access to the Blob and File service. 或者您可以建立委派存取給全部四個服務 (Blob、佇列、表格和檔案) 的 SAS。Or you can create a SAS that delegates access to all four services (Blob, Queue, Table, and File).
  • 儲存體資源類型。Storage resource types. 帳戶 SAS 適用於一或多個類別的儲存體資源,而不是特定資源。An account SAS applies to one or more classes of storage resources, rather than a specific resource. 您可以建立帳戶 SAS 來委派存取給:You can create an account SAS to delegate access to:
    • 對儲存體帳戶資源呼叫的服務層級 API。Service-level APIs, which are called against the storage account resource. 範例包括取得/設定服務屬性取得服務統計資料列出容器/佇列/資料表/共用Examples include Get/Set Service Properties, Get Service Stats, and List Containers/Queues/Tables/Shares.
    • 容器層級 API,會針對每個服務的容器物件呼叫:Blob 容器、佇列、資料表和檔案共用。Container-level APIs, which are called against the container objects for each service: blob containers, queues, tables, and file shares. 範例包括建立/刪除容器建立/刪除佇列建立/刪除資料表建立/刪除共用列出 Blob/檔案和目錄Examples include Create/Delete Container, Create/Delete Queue, Create/Delete Table, Create/Delete Share, and List Blobs/Files and Directories.
    • 物件層級 API,針對 Blob、佇列訊息、資料表實體和檔案呼叫。Object-level APIs, which are called against blobs, queue messages, table entities, and files. 例如,放置 Blob查詢實體取得訊息建立檔案For example, Put Blob, Query Entity, Get Messages, and Create File.

SAS URI 的範例Examples of SAS URIs

服務 SAS URI 範例Service SAS URI example

以下是提供讀取和寫入 Blob 權限的服務 SAS URI 範例。Here is an example of a service SAS URI that provides read and write permissions to a blob. 此資料表會細分 URI 的每一部分,以了解它會如何影響 SAS:The table breaks down each part of the URI to understand how it contributes to the SAS:

https://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D
NameName SAS 部分SAS portion 描述Description
Blob URIBlob URI https://myaccount.blob.core.windows.net/sascontainer/sasblob.txt Blob 的位址。The address of the blob. 請注意,我們強烈建議您使用 HTTPS。Note that using HTTPS is highly recommended.
儲存體服務版本Storage services version sv=2015-04-05 若是儲存體服務版本 2012-02-12 和更新版本,此參數表示要使用的版本。For storage services version 2012-02-12 and later, this parameter indicates the version to use.
開始時間Start time st=2015-04-29T22%3A18%3A26Z 以 UTC 時間指定。Specified in UTC time. 如果您想要 SAS 立即生效,請略過開始時間。If you want the SAS to be valid immediately, omit the start time.
過期時間Expiry time se=2015-04-30T02%3A23%3A26Z 以 UTC 時間指定。Specified in UTC time.
資源Resource sr=b 此資源是 Blob。The resource is a blob.
權限Permissions sp=rw SAS 所授與的權限包括讀取 (r) 和寫入 (w)。The permissions granted by the SAS include Read (r) and Write (w).
IP 範圍IP range sip=168.1.5.60-168.1.5.70 將從中接受要求的 IP 位址範圍。The range of IP addresses from which a request will be accepted.
ProtocolProtocol spr=https 僅允許使用 HTTPS 的要求。Only requests using HTTPS are permitted.
簽章Signature sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D 用來授權存取 Blob。Used to authorize access to the blob. 此簽章是 HMAC 根據要簽署字串和金鑰,使用 SHA256 演算法進行計算,然後使用 Base64 方式進行編碼而來的。The signature is an HMAC computed over a string-to-sign and key using the SHA256 algorithm, and then encoded using Base64 encoding.

帳戶 SAS URI 範例Account SAS URI example

以下是對權杖使用相同通用參數的帳戶 SAS 範例。Here is an example of an account SAS that uses the same common parameters on the token. 由於上面說明了這些參數,在此處將不說明。Since these parameters are described above, they are not described here. 下表只會說明帳戶 SAS 的特定參數。Only the parameters that are specific to account SAS are described in the table below.

https://myaccount.blob.core.windows.net/?restype=service&comp=properties&sv=2015-04-05&ss=bf&srt=s&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=F%6GRVAZ5Cdj2Pw4tgU7IlSTkWgn7bUkkAg8P6HESXwmf%4B
NameName SAS 部分SAS portion 描述Description
資源 URIResource URI https://myaccount.blob.core.windows.net/?restype=service&comp=properties Blob 服務端點,具有用來取得服務屬性 (使用 GET 呼叫時) 或設定服務屬性 (使用 SET 呼叫時) 的參數。The Blob service endpoint, with parameters for getting service properties (when called with GET) or setting service properties (when called with SET).
服務Services ss=bf SAS 適用於 Blob 和檔案服務The SAS applies to the Blob and File services
資源類型Resource types srt=s SAS 適用於服務層級的作業。The SAS applies to service-level operations.
權限Permissions sp=rw 此權限可授與讀取和寫入作業的存取權。The permissions grant access to read and write operations.

假設權限僅限於服務層級,此 SAS 可存取的作業是取得 Blob 服務屬性 (讀取) 和設定 Blob 服務屬性 (寫入)。Given that permissions are restricted to the service level, accessible operations with this SAS are Get Blob Service Properties (read) and Set Blob Service Properties (write). 不過,利用不同的資源 URI,相同的 SAS 權杖也可以用來委派存取給 取得 Blob 服務統計資料 (讀取)。However, with a different resource URI, the same SAS token could also be used to delegate access to Get Blob Service Stats (read).

使用預存存取原則控制 SASControlling a SAS with a stored access policy

共用存取簽章可以接受以下兩種格式其中之一:A shared access signature can take one of two forms:

  • 臨機操作 SAS: 建立臨機操作 SAS 時,SAS 的開始時間、過期時間和權限都會在 SAS URI 上進行指定 (或暗示,在此情況下則會略過開始時間)。Ad hoc SAS: When you create an ad hoc SAS, the start time, expiry time, and permissions for the SAS are all specified in the SAS URI (or implied, in the case where start time is omitted). 這種類型的 SAS 可能會建立為帳戶 SAS 或服務 SAS。This type of SAS can be created as an account SAS or a service SAS.
  • 含預存存取原則的 SAS: 預存存取原則會在資源容器 (Blob 容器、資料表、佇列或檔案共用) 中定義,且可用來管理一或多個共用存取簽章的限制。SAS with stored access policy: A stored access policy is defined on a resource container--a blob container, table, queue, or file share--and can be used to manage constraints for one or more shared access signatures. 當您將 SAS 與預存存取原則建立關聯時,SAS 會繼承為該預存存取原則所定義的限制 (開始時間、過期時間和權限)。When you associate a SAS with a stored access policy, the SAS inherits the constraints--the start time, expiry time, and permissions--defined for the stored access policy.

注意

目前,帳戶 SAS 必須是臨機操作 SAS。Currently, an account SAS must be an ad hoc SAS. 帳戶 SAS 尚不支援預存的存取原則。Stored access policies are not yet supported for account SAS.

這兩種格式間的差異對於以下這一個重要案例而言相當重要:撤銷。The difference between the two forms is important for one key scenario: revocation. SAS URI 為 URL,因此無論其原始建立者為何,任何人只要取得 SAS 即可自由使用。Because a SAS URI is a URL, anyone that obtains the SAS can use it, regardless of who originally created it. 如果是公開發佈 SAS,則全世界的人都可以使用此 SAS。If a SAS is published publicly, it can be used by anyone in the world. 除非發生下述四種情況之一,否則 SAS 會將資源存取權授與具有 SAS 的任何人:A SAS grants access to resources to anyone possessing it until one of four things happens:

  1. 已到達 SAS 上指定的過期時間。The expiry time specified on the SAS is reached.
  2. 已到達在 SAS 所參考之預存存取原則上所指定的過期時間 (如果參考的是預存存取原則,而且如果此預存存取原則指定了過期時間)。The expiry time specified on the stored access policy referenced by the SAS is reached (if a stored access policy is referenced, and if it specifies an expiry time). 發生此情況的原因,有可能是因為已超過指定的間隔時間,或是因為您已修改預存存取原則,將過期時間設定為過去的日期,這是撤銷 SAS 的一種方法。This can occur either because the interval elapses, or because you've modified the stored access policy with an expiry time in the past, which is one way to revoke the SAS.
  3. 已刪除 SAS 所參考之預存存取原則,這是撤銷 SAS 的另外一種方法。The stored access policy referenced by the SAS is deleted, which is another way to revoke the SAS. 請注意,如果您使用完全相同的名稱來重新建立預存存取原則,則現有的所有 SAS 權杖會根據與該預存存取原則有關的權限再次有效 (假設 SAS 上的過期時間尚未過去)。Note that if you recreate the stored access policy with exactly the same name, all existing SAS tokens will again be valid according to the permissions associated with that stored access policy (assuming that the expiry time on the SAS has not passed). 如果您打算撤銷 SAS,且如果您要使用未來的過期時間來重新建立存取原則,則務必使用不同的名稱。If you are intending to revoke the SAS, be sure to use a different name if you recreate the access policy with an expiry time in the future.
  4. 系統會重新產生用來建立 SAS 的帳戶金鑰。The account key that was used to create the SAS is regenerated. 重新產生帳戶金鑰將導致所有使用該金鑰的應用程式元件無法授權,直到它們已更新為使用其他有效帳戶金鑰或最近重新產生的帳戶金鑰為止。Regenerating an account key will cause all application components using that key to fail to authorize until they're updated to use either the other valid account key or the newly regenerated account key.

重要

共用存取簽章 URI 會與用來建立簽章的帳戶金鑰,以及相關聯的預存的存取原則 (如果有的話) 產生關聯。A shared access signature URI is associated with the account key used to create the signature, and the associated stored access policy (if any). 如果未指定任何預存的存取原則,則撤銷共用存取簽章的唯一方式是變更帳戶金鑰。If no stored access policy is specified, the only way to revoke a shared access signature is to change the account key.

使用 SAS 從用戶端應用程式進行驗證Authenticating from a client application with a SAS

擁有 SAS 的用戶端可以使用 SAS 來對他們未擁有帳戶金鑰的儲存體帳戶授權要求。A client who is in possession of a SAS can use the SAS to authorize a request against a storage account for which they do not possess the account keys. SAS 可以包含在連接字串,或直接從適當的建構函式或方法來使用。A SAS can be included in a connection string, or used directly from the appropriate constructor or method.

在連接字串中使用 SASUsing a SAS in a connection string

如果您具有授與您存取儲存體帳戶中資源的共用存取簽章 (SAS) URL,您可以在連接字串中使用 SAS。If you possess a shared access signature (SAS) URL that grants you access to resources in a storage account, you can use the SAS in a connection string. 因為 SAS 包含驗證要求所需的資訊,所以含有 SAS 的連接字串會提供通訊協定、服務端點,以及存取資源所需的認證。Because the SAS contains the information required to authenticate the request, a connection string with a SAS provides the protocol, the service endpoint, and the necessary credentials to access the resource.

若要建立包含共用存取簽章的連接字串,請以下列格式指定字串:To create a connection string that includes a shared access signature, specify the string in the following format:

BlobEndpoint=myBlobEndpoint;
QueueEndpoint=myQueueEndpoint;
TableEndpoint=myTableEndpoint;
FileEndpoint=myFileEndpoint;
SharedAccessSignature=sasToken

雖然連接字串必須包含至少一個服務端點,但是每個服務端點都是選用的。Each service endpoint is optional, although the connection string must contain at least one.

注意

建議最好搭配使用 HTTPS 與 SAS。Using HTTPS with a SAS is recommended as a best practice.

如果您在組態檔的連接字串中指定 SAS,則可能需要編碼 URL 中的特殊字元。If you are specifying a SAS in a connection string in a configuration file, you may need to encode special characters in the URL.

服務 SAS 範例Service SAS example

以下範例是包含服務 SAS for Blob 儲存體的連接字串:Here's an example of a connection string that includes a service SAS for Blob storage:

BlobEndpoint=https://storagesample.blob.core.windows.net;
SharedAccessSignature=sv=2015-04-05&sr=b&si=tutorial-policy-635959936145100803&sig=9aCzs76n0E7y5BpEi2GvsSv433BZa22leDOZXX%2BXXIU%3D

而以下範例是具有特殊字元編碼的相同連接字串︰And here's an example of the same connection string with encoding of special characters:

BlobEndpoint=https://storagesample.blob.core.windows.net;
SharedAccessSignature=sv=2015-04-05&sr=b&si=tutorial-policy-635959936145100803&sig=9aCzs76n0E7y5BpEi2GvsSv433BZa22leDOZXX%2BXXIU%3D

帳戶 SAS 範例Account SAS example

以下範例是包含帳戶 SAS for Blob 和檔案儲存體的連接字串。Here's an example of a connection string that includes an account SAS for Blob and File storage. 請注意,指定兩個服務的端點︰Note that endpoints for both services are specified:

BlobEndpoint=https://storagesample.blob.core.windows.net;
FileEndpoint=https://storagesample.file.core.windows.net;
SharedAccessSignature=sv=2015-07-08&sig=iCvQmdZngZNW%2F4vw43j6%2BVz6fndHF5LI639QJba4r8o%3D&spr=https&st=2016-04-12T03%3A24%3A31Z&se=2016-04-13T03%3A29%3A31Z&srt=s&ss=bf&sp=rwl

而以下範例是具有 URL 編碼的相同連接字串︰And here's an example of the same connection string with URL encoding:

BlobEndpoint=https://storagesample.blob.core.windows.net;
FileEndpoint=https://storagesample.file.core.windows.net;
SharedAccessSignature=sv=2015-07-08&sig=iCvQmdZngZNW%2F4vw43j6%2BVz6fndHF5LI639QJba4r8o%3D&spr=https&st=2016-04-12T03%3A24%3A31Z&se=2016-04-13T03%3A29%3A31Z&srt=s&ss=bf&sp=rwl

在建構函式或方法中使用 SASUsing a SAS in a constructor or method

數個 Azure 儲存體用戶端程式庫的建構函式和方法多載會提供 SAS 參數,以便您使用 SAS 來授權對服務的要求。Several Azure Storage client library constructors and method overloads offer a SAS parameter, so that you can authorize a request to the service with a SAS.

例如,這裡便使用 SAS URI 來建立區塊 Blob 的參考。For example, here a SAS URI is used to create a reference to a block blob. SAS 提供要求所需的唯一認證。The SAS provides the only credentials needed for the request. 區塊 Blob 參考接著會用來進行寫入作業︰The block blob reference is then used for a write operation:

string sasUri = "https://storagesample.blob.core.windows.net/sample-container/" +
    "sampleBlob.txt?sv=2015-07-08&sr=b&sig=39Up9JzHkxhUIhFEjEH9594DJxe7w6cIRCg0V6lCGSo%3D" +
    "&se=2016-10-18T21%3A51%3A37Z&sp=rcw";

CloudBlockBlob blob = new CloudBlockBlob(new Uri(sasUri));

// Create operation: Upload a blob with the specified name to the container.
// If the blob does not exist, it will be created. If it does exist, it will be overwritten.
try
{
    MemoryStream msWrite = new MemoryStream(Encoding.UTF8.GetBytes(blobContent));
    msWrite.Position = 0;
    using (msWrite)
    {
        await blob.UploadFromStreamAsync(msWrite);
    }

    Console.WriteLine("Create operation succeeded for SAS {0}", sasUri);
    Console.WriteLine();
}
catch (StorageException e)
{
    if (e.RequestInformation.HttpStatusCode == 403)
    {
        Console.WriteLine("Create operation failed for SAS {0}", sasUri);
        Console.WriteLine("Additional error information: " + e.Message);
        Console.WriteLine();
    }
    else
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

使用 SAS 時的最佳做法Best practices when using SAS

當您在應用程式中使用共用存取簽章時,您必須留意兩個潛在風險:When you use shared access signatures in your applications, you need to be aware of two potential risks:

  • 如果 SAS 洩漏出去,則取得該 SAS 的任何人都可以使用它,這有可能會洩露您的儲存體帳戶。If a SAS is leaked, it can be used by anyone who obtains it, which can potentially compromise your storage account.
  • 如果提供給用戶端應用程式的 SAS 已過期,且此應用程式無法從您的服務擷取新的 SAS,那麼該應用程式的功能可能會受到影響。If a SAS provided to a client application expires and the application is unable to retrieve a new SAS from your service, then the application's functionality may be hindered.

下列關於使用共用存取簽章的建議,將可協助您平衡這些風險:The following recommendations for using shared access signatures can help mitigate these risks:

  1. 永遠使用 HTTPS 來建立或散佈 SAS。Always use HTTPS to create or distribute a SAS. 若透過 HTTP 來傳遞 SAS 並遭到攔截,執行攔截式攻擊的攻擊者即可讀取並使用 SAS (就如同預期使用者執行般),這有可能會洩露敏感資料或允許惡意使用者損毀資料。If a SAS is passed over HTTP and intercepted, an attacker performing a man-in-the-middle attack is able to read the SAS and then use it just as the intended user could have, potentially compromising sensitive data or allowing for data corruption by the malicious user.
  2. 可能的話,參考預存存取原則。Reference stored access policies where possible. 預存存取原則提供了撤銷權限且無需重新產生儲存體帳戶金鑰的選項。Stored access policies give you the option to revoke permissions without having to regenerate the storage account keys. 將到期日設在未來 (或無限) 的日期,並確定定期更新到期日以將到期日再往未來的日期移動。Set the expiration on these very far in the future (or infinite) and make sure it's regularly updated to move it farther into the future.
  3. 在臨機操作 SAS 上使用短期的到期時間。Use near-term expiration times on an ad hoc SAS. 如此一來,即使 SAS 遭到入侵,亦僅會造成短期影響。In this way, even if a SAS is compromised, it's valid only for a short time. 如果您無法參考預存存取原則,此做法格外重要。This practice is especially important if you cannot reference a stored access policy. 短期到期時間亦可協助限制可寫入 Blob 的資料量,方法是限制可對其上傳的可用時間。Near-term expiration times also limit the amount of data that can be written to a blob by limiting the time available to upload to it.
  4. 讓用戶端視需要自動更新 SAS。Have clients automatically renew the SAS if necessary. 用戶端應在到期日之前就更新 SAS,以便如果提供 SAS 的服務無法使用的話,還有時間可以進行重試。Clients should renew the SAS well before the expiration, in order to allow time for retries if the service providing the SAS is unavailable. 如果您打算將 SAS 用於少量的即時短期操作 (預計可在到期期限內完成的操作),則此建議可能沒有必要,因為沒有更新 SAS 的打算。If your SAS is meant to be used for a small number of immediate, short-lived operations that are expected to be completed within the expiration period, then this may be unnecessary as the SAS is not expected to be renewed. 不過,如果您有定期透過 SAS 做出要求的用戶端,則到期的可能性便有可能發生。However, if you have client that is routinely making requests via SAS, then the possibility of expiration comes into play. 主要考量是要平衡下列兩個需求:短期的 SAS (如先前所述),與確保用戶端提早要求更新以避免成功更新之前因 SAS 過期而中斷。The key consideration is to balance the need for the SAS to be short-lived (as previously stated) with the need to ensure that the client is requesting renewal early enough (to avoid disruption due to the SAS expiring prior to successful renewal).
  5. 請小心使用 SAS 開始時間。Be careful with SAS start time. 如果您將 SAS 的開始時間設為 [現在] ,則由於時鐘誤差 (根據不同機器會有不同的目前時間),前幾分鐘可能偶爾會被視為失敗。If you set the start time for a SAS to now, then due to clock skew (differences in current time according to different machines), failures may be observed intermittently for the first few minutes. 一般而言,請將開始時間設為至少 15 分鐘之前的時間。In general, set the start time to be at least 15 minutes in the past. 或是不進行任何設定,這會針對所有案例立即生效。Or, don't set it at all, which will make it valid immediately in all cases. 同樣的道理通常亦適用於過期時間,請記住,您可針對任何要求保留前後多達 15 分鐘的時鐘誤差。The same generally applies to expiry time as well--remember that you may observe up to 15 minutes of clock skew in either direction on any request. 若是用戶端使用 2012-02-12 之前的 REST 版本,則不參考預存存取原則之 SAS 的最大持續期限是 1 個小時,且任何指定比 1 個小時還要長的原則都會失敗。For clients using a REST version prior to 2012-02-12, the maximum duration for a SAS that does not reference a stored access policy is 1 hour, and any policies specifying longer term than that will fail.
  6. 請具體指出要存取的資源。Be specific with the resource to be accessed. 安全性最佳做法是提供使用者最低需求權限。A security best practice is to provide a user with the minimum required privileges. 如果使用者只需要單一實體的讀取存取權,則授與他們該單一實體的讀取存取權,而非授與他們所有實體的讀取/寫入/刪除存取權。If a user only needs read access to a single entity, then grant them read access to that single entity, and not read/write/delete access to all entities. 這有助於減輕洩露 SAS 遭受的損害,因為當 SAS 落入攻擊者手中時,即無法發揮固有功能。This also helps lessen the damage if a SAS is compromised because the SAS has less power in the hands of an attacker.
  7. 了解您帳戶的任何方式將會被收取費用,包括以 SAS 方式完成的部分。Understand that your account will be billed for any usage, including that done with SAS. 如果您提供 Blob 的寫入存取權,則使用者可能會選擇上傳 200GB 的 Blob。If you provide write access to a blob, a user may choose to upload a 200GB blob. 若您也同時提供使用者讀取存取權,則他們可能會選擇下載 10 次,而您便會產生 2TB 的出口成本。If you've given them read access as well, they may choose to download it 10 times, incurring 2 TB in egress costs for you. 再次強調,提供有限的權限有助於減少惡意使用者採取的潛在動作。Again, provide limited permissions to help mitigate the potential actions of malicious users. 使用短期 SAS 以降低此威脅 (但請注意結束時間的時鐘誤差)。Use short-lived SAS to reduce this threat (but be mindful of clock skew on the end time).
  8. 使用 SAS 驗證寫入資料。Validate data written using SAS. 當用戶端應用程式將資料寫入您的儲存體帳戶時,請留意該資料可能會造成問題。When a client application writes data to your storage account, keep in mind that there can be problems with that data. 如果您的應用程式要求在開始使用資料之前先驗證或授權資料,則您應在寫入資料之後但應用程式尚未開始使用資料之前執行此驗證。If your application requires that data be validated or authorized before it is ready to use, you should perform this validation after the data is written and before it is used by your application. 此做法也可防止正確取得 SAS 的使用者或是利用洩漏 SAS 的使用者,損毀資料或將惡意資料寫入您的帳戶。This practice also protects against corrupt or malicious data being written to your account, either by a user who properly acquired the SAS, or by a user exploiting a leaked SAS.
  9. 請勿一直使用 SAS。Don't always use SAS. 有時候,在儲存體帳戶中執行特定作業的相關風險可能大過 SAS 的好處。Sometimes the risks associated with a particular operation against your storage account outweigh the benefits of SAS. 針對此類作業,請建立一個中介層服務,在執行商務規則驗證、驗證及稽核之後才寫入您的儲存體帳戶。For such operations, create a middle-tier service that writes to your storage account after performing business rule validation, authentication, and auditing. 另外,有時候以其他方式管理存取權可能比較簡單。Also, sometimes it's simpler to manage access in other ways. 例如,如果您想要讓容器中的所有 Blob 都可供公開讀取,則您可以將此容器設定為 [公用],而不是將 SAS 提供給每個用戶端進行存取。For example, if you want to make all blobs in a container publicly readable, you can make the container Public, rather than providing a SAS to every client for access.
  10. 使用儲存體分析來監視您的應用程式。Use Storage Analytics to monitor your application. 您可以使用記錄和度量來觀察由於 SAS 提供者服務中斷或不小心移除預存存取原則,而造成的任何驗證失敗急劇增加。You can use logging and metrics to observe any spike in authentication failures due to an outage in your SAS provider service or to the inadvertent removal of a stored access policy. 如需額外資訊,請參閱 Azure 儲存體團隊部落格 (英文)。See the Azure Storage Team Blog for additional information.

SAS 範例SAS examples

下面是兩種類型共用存取簽章 (帳戶 SAS 和服務 SAS) 的一些範例。Below are some examples of both types of shared access signatures, account SAS and service SAS.

若要執行這些 C# 範例,您必須參考專案中的下列 NuGet 封裝︰To run these C# examples, you need to reference the following NuGet packages in your project:

如需其他範例,示範如何建立及測試 SAS,請參閱 Azure 儲存體的程式碼範例For additional examples that show how to create and test a SAS, see Azure Code Samples for Storage.

範例:建立和使用帳戶 SASExample: Create and use an account SAS

下列程式碼範例會建立適用於 Blob 和檔案服務的帳戶 SAS,並提供用戶端權限讀取、寫入和列出權限來存取服務層級 API。The following code example creates an account SAS that is valid for the Blob and File services, and gives the client permissions read, write, and list permissions to access service-level APIs. 帳戶 SAS 會將通訊協定限制為 HTTPS,因此必須使用 HTTPS 提出要求。The account SAS restricts the protocol to HTTPS, so the request must be made with HTTPS.

static string GetAccountSASToken()
{
    // To create the account SAS, you need to use your shared key credentials. Modify for your account.
    const string ConnectionString = "DefaultEndpointsProtocol=https;AccountName=account-name;AccountKey=account-key";
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConnectionString);

    // Create a new access policy for the account.
    SharedAccessAccountPolicy policy = new SharedAccessAccountPolicy()
        {
            Permissions = SharedAccessAccountPermissions.Read | SharedAccessAccountPermissions.Write | SharedAccessAccountPermissions.List,
            Services = SharedAccessAccountServices.Blob | SharedAccessAccountServices.File,
            ResourceTypes = SharedAccessAccountResourceTypes.Service,
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
            Protocols = SharedAccessProtocol.HttpsOnly
        };

    // Return the SAS token.
    return storageAccount.GetSharedAccessSignature(policy);
}

若要使用 帳戶 SAS 來存取 Blob 服務的服務層級 API,請使用 SAS 及儲存體帳戶的 Blob 儲存體端點來建構 Blob 用戶端物件。To use the account SAS to access service-level APIs for the Blob service, construct a Blob client object using the SAS and the Blob storage endpoint for your storage account.

static void UseAccountSAS(string sasToken)
{
    // Create new storage credentials using the SAS token.
    StorageCredentials accountSAS = new StorageCredentials(sasToken);
    // Use these credentials and the account name to create a Blob service client.
    CloudStorageAccount accountWithSAS = new CloudStorageAccount(accountSAS, "account-name", endpointSuffix: null, useHttps: true);
    CloudBlobClient blobClientWithSAS = accountWithSAS.CreateCloudBlobClient();

    // Now set the service properties for the Blob client created with the SAS.
    blobClientWithSAS.SetServiceProperties(new ServiceProperties()
    {
        HourMetrics = new MetricsProperties()
        {
            MetricsLevel = MetricsLevel.ServiceAndApi,
            RetentionDays = 7,
            Version = "1.0"
        },
        MinuteMetrics = new MetricsProperties()
        {
            MetricsLevel = MetricsLevel.ServiceAndApi,
            RetentionDays = 7,
            Version = "1.0"
        },
        Logging = new LoggingProperties()
        {
            LoggingOperations = LoggingOperations.All,
            RetentionDays = 14,
            Version = "1.0"
        }
    });

    // The permissions granted by the account SAS also permit you to retrieve service properties.
    ServiceProperties serviceProperties = blobClientWithSAS.GetServiceProperties();
    Console.WriteLine(serviceProperties.HourMetrics.MetricsLevel);
    Console.WriteLine(serviceProperties.HourMetrics.RetentionDays);
    Console.WriteLine(serviceProperties.HourMetrics.Version);
}

範例:建立預存的存取原則Example: Create a stored access policy

下列程式碼會在容器上建立預存的存取原則。The following code creates a stored access policy on a container. 您可以使用存取原則,對於容器上的服務 SAS 或其 Blob 指定條件約束。You can use the access policy to specify constraints for a service SAS on the container or its blobs.

private static async Task CreateSharedAccessPolicyAsync(CloudBlobContainer container, string policyName)
{
    // Create a new shared access policy and define its constraints.
    // The access policy provides create, write, read, list, and delete permissions.
    SharedAccessBlobPolicy sharedPolicy = new SharedAccessBlobPolicy()
    {
        // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
        // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
        SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
        Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.List |
            SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create | SharedAccessBlobPermissions.Delete
    };

    // Get the container's existing permissions.
    BlobContainerPermissions permissions = await container.GetPermissionsAsync();

    // Add the new policy to the container's permissions, and set the container's permissions.
    permissions.SharedAccessPolicies.Add(policyName, sharedPolicy);
    await container.SetPermissionsAsync(permissions);
}

範例:在容器上建立服務 SASExample: Create a service SAS on a container

下列程式碼會在容器上建立 SAS。The following code creates a SAS on a container. 如果提供現有預存存取原則的名稱,該原則將與 SAS 相關聯。If the name of an existing stored access policy is provided, that policy is associated with the SAS. 如果未不提供任何預存的存取原則,則程式碼會建立臨機操作 SAS 的容器上。If no stored access policy is provided, then the code creates an ad hoc SAS on the container.

private static string GetContainerSasUri(CloudBlobContainer container, string storedPolicyName = null)
{
    string sasContainerToken;

    // If no stored policy is specified, create a new access policy and define its constraints.
    if (storedPolicyName == null)
    {
        // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
        // to construct a shared access policy that is saved to the container's shared access policies.
        SharedAccessBlobPolicy adHocPolicy = new SharedAccessBlobPolicy()
        {
            // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
            // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
            Permissions = SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.List
        };

        // Generate the shared access signature on the container, setting the constraints directly on the signature.
        sasContainerToken = container.GetSharedAccessSignature(adHocPolicy, null);

        Console.WriteLine("SAS for blob container (ad hoc): {0}", sasContainerToken);
        Console.WriteLine();
    }
    else
    {
        // Generate the shared access signature on the container. In this case, all of the constraints for the
        // shared access signature are specified on the stored access policy, which is provided by name.
        // It is also possible to specify some constraints on an ad hoc SAS and others on the stored access policy.
        sasContainerToken = container.GetSharedAccessSignature(null, storedPolicyName);

        Console.WriteLine("SAS for blob container (stored access policy): {0}", sasContainerToken);
        Console.WriteLine();
    }

    // Return the URI string for the container, including the SAS token.
    return container.Uri + sasContainerToken;
}

範例:在 Blob 上建立服務 SASExample: Create a service SAS on a blob

下列程式碼會在 Blob 上建立 SAS。The following code creates a SAS on a blob. 如果提供現有預存存取原則的名稱,該原則將與 SAS 相關聯。If the name of an existing stored access policy is provided, that policy is associated with the SAS. 如果未不提供任何預存的存取原則,則程式碼會建立臨機操作 SAS 上的 blob。If no stored access policy is provided, then the code creates an ad hoc SAS on the blob.

private static string GetBlobSasUri(CloudBlobContainer container, string blobName, string policyName = null)
{
    string sasBlobToken;

    // Get a reference to a blob within the container.
    // Note that the blob may not exist yet, but a SAS can still be created for it.
    CloudBlockBlob blob = container.GetBlockBlobReference(blobName);

    if (policyName == null)
    {
        // Create a new access policy and define its constraints.
        // Note that the SharedAccessBlobPolicy class is used both to define the parameters of an ad hoc SAS, and
        // to construct a shared access policy that is saved to the container's shared access policies.
        SharedAccessBlobPolicy adHocSAS = new SharedAccessBlobPolicy()
        {
            // When the start time for the SAS is omitted, the start time is assumed to be the time when the storage service receives the request.
            // Omitting the start time for a SAS that is effective immediately helps to avoid clock skew.
            SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24),
            Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write | SharedAccessBlobPermissions.Create
        };

        // Generate the shared access signature on the blob, setting the constraints directly on the signature.
        sasBlobToken = blob.GetSharedAccessSignature(adHocSAS);

        Console.WriteLine("SAS for blob (ad hoc): {0}", sasBlobToken);
        Console.WriteLine();
    }
    else
    {
        // Generate the shared access signature on the blob. In this case, all of the constraints for the
        // shared access signature are specified on the container's stored access policy.
        sasBlobToken = blob.GetSharedAccessSignature(null, policyName);

        Console.WriteLine("SAS for blob (stored access policy): {0}", sasBlobToken);
        Console.WriteLine();
    }

    // Return the URI string for the container, including the SAS token.
    return blob.Uri + sasBlobToken;
}

結論Conclusion

若要提供您儲存體帳戶的有限權限給沒有帳戶金鑰的用戶端,則共用存取簽章是非常有用的方式。Shared access signatures are useful for providing limited permissions to your storage account to clients that should not have the account key. 因此,對於任何使用 Azure 儲存體的應用程式而言,共用存取簽章是安全性模型不可或缺的一部分。As such, they are a vital part of the security model for any application using Azure Storage. 如果您依照此處所列的最佳做法進行,則您可以使用 SAS 來提供更大的彈性以存取儲存體帳戶中的資源,且不會影響應用程式的安全性。If you follow the best practices listed here, you can use SAS to provide greater flexibility of access to resources in your storage account, without compromising the security of your application.

後續步驟Next Steps