您现在访问的是微软AZURE全球版技术文档网站,若需要访问由世纪互联运营的MICROSOFT AZURE中国区技术文档网站,请访问 https://docs.azure.cn.

安全访问云中的应用程序数据Secure access to an application's data in the cloud

本教程是一个系列中的第三部分。This tutorial is part three of a series. 你将了解如何安全访问存储帐户。You learn how to secure access to the storage account.

在该系列的第三部分中,你会学习如何:In part three of the series, you learn how to:

  • 使用 SAS 令牌访问缩略图图像Use SAS tokens to access thumbnail images
  • 启用服务器端加密Turn on server-side encryption
  • 启用仅 HTTPS 传输Enable HTTPS-only transport

Azure blob 存储提供存储应用程序文件的可靠服务。Azure blob storage provides a robust service to store files for applications. 此教程对上一个主题进行扩展,演示如何从 Web 应用程序安全访问存储帐户。This tutorial extends the previous topic to show how to secure access to your storage account from a web application. 完成后,图像会被加密,Web 应用使用安全的 SAS 令牌访问缩略图图像。When you're finished the images are encrypted and the web app uses secure SAS tokens to access the thumbnail images.

先决条件Prerequisites

若要完成本教程,必须先完成上一存储教程:使用事件网格自动调整上传图像的大小To complete this tutorial you must have completed the previous Storage tutorial: Automate resizing uploaded images using Event Grid.

设置容器公共访问权限Set container public access

在系列教程的此部分中,SAS 令牌用于访问缩略图。In this part of the tutorial series, SAS tokens are used for accessing the thumbnails. 在此步骤中,请将 thumbnails 容器的公共访问权限设置为 offIn this step, you set the public access of the thumbnails container to off.

blobStorageAccount=<blob_storage_account>

blobStorageAccountKey=$(az storage account keys list -g myResourceGroup \
-n $blobStorageAccount --query [0].value --output tsv) 

az storage container set-permission \ --account-name $blobStorageAccount \ --account-key $blobStorageAccountKey \ --name thumbnails  \
--public-access off

为缩略图配置 SAS 令牌Configure SAS tokens for thumbnails

在本系列教程的第一部分中,Web 应用程序显示公共容器中的图像。In part one of this tutorial series, the web application was showing images from a public container. 在此系列教程的这个部分中,请使用共享访问签名 (SAS) 令牌检索缩略图图像。In this part of the series, you use Shared Access Signature (SAS) tokens to retrieve the thumbnail images. 通过 SAS 令牌,可以实现基于 IP、协议、时间间隔或允许的权限提供对容器或 blob 的受限访问权限。SAS tokens allow you to provide restricted access to a container or blob based on IP, protocol, time interval, or rights allowed.

此示例中,源代码存储库使用 sasTokens 分支,该分支有更新的代码示例。In this example, the source code repository uses the sasTokens branch, which has an updated code sample. 使用 az webapp deployment source delete 删除现有的 GitHub 部署。Delete the existing GitHub deployment with the az webapp deployment source delete. 然后,使用 az webapp deployment source config 命令配置 Web 应用的 GitHub 部署。Next, configure GitHub deployment to the web app with the az webapp deployment source config command.

在下面的命令中,<web-app> 是 Web 应用的名称。In the following command, <web-app> is the name of your web app.

az webapp deployment source delete --name <web-app> --resource-group myResourceGroup

az webapp deployment source config --name <web_app> \
--resource-group myResourceGroup --branch sasTokens --manual-integration \
--repo-url https://github.com/Azure-Samples/storage-blob-upload-from-webapp

存储库的 sasTokens 分支更新了 StorageHelper.cs 文件。The sasTokens branch of the repository updates the StorageHelper.cs file. 它将使用下面的代码示例替换 GetThumbNailUrls 任务。It replaces the GetThumbNailUrls task with the code example below. 通过设置 SharedAccessBlobPolicy 指定 SAS 令牌的开始时间、到期时间和权限,更新的任务会检索缩略图 URL。The updated task retrieves the thumbnail URLs by setting a SharedAccessBlobPolicy to specify the start time, expiry time, and permissions for the SAS token. 部署 Web 应用后,使用 SAS 令牌检索带 URL 的缩略图。Once deployed the web app now retrieves the thumbnails with a URL using a SAS token. 以下示例显示已更新任务:The updated task is shown in the following example:

public static async Task<List<string>> GetThumbNailUrls(AzureStorageConfig _storageConfig)
{
    List<string> thumbnailUrls = new List<string>();

    // Create storagecredentials object by reading the values from the configuration (appsettings.json)
    StorageCredentials storageCredentials = new StorageCredentials(_storageConfig.AccountName, _storageConfig.AccountKey);

    // Create cloudstorage account by passing the storagecredentials
    CloudStorageAccount storageAccount = new CloudStorageAccount(storageCredentials, true);

    // Create blob client
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Get reference to the container
    CloudBlobContainer container = blobClient.GetContainerReference(_storageConfig.ThumbnailContainer);

    BlobContinuationToken continuationToken = null;

    BlobResultSegment resultSegment = null;

    //Call ListBlobsSegmentedAsync and enumerate the result segment returned, while the continuation token is non-null.
    //When the continuation token is null, the last page has been returned and execution can exit the loop.
    do
    {
        //This overload allows control of the page size. You can return all remaining results by passing null for the maxResults parameter,
        //or by calling a different overload.
        resultSegment = await container.ListBlobsSegmentedAsync("", true, BlobListingDetails.All, 10, continuationToken, null, null);

        foreach (var blobItem in resultSegment.Results)
        {
            CloudBlockBlob blob = blobItem as CloudBlockBlob;
            //Set the expiry time and permissions for the blob.
            //In this case, the start time is specified as a few minutes in the past, to mitigate clock skew.
            //The shared access signature will be valid immediately.
            SharedAccessBlobPolicy sasConstraints = new SharedAccessBlobPolicy();

            sasConstraints.SharedAccessStartTime = DateTimeOffset.UtcNow.AddMinutes(-5);

            sasConstraints.SharedAccessExpiryTime = DateTimeOffset.UtcNow.AddHours(24);

            sasConstraints.Permissions = SharedAccessBlobPermissions.Read;

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

            //Return the URI string for the container, including the SAS token.
            thumbnailUrls.Add(blob.Uri + sasBlobToken);

        }

        //Get the continuation token.
        continuationToken = resultSegment.ContinuationToken;
    }

    while (continuationToken != null);

    return await Task.FromResult(thumbnailUrls);
}

以下是用于前一任务的类、属性和方法:The following classes, properties, and methods are used in the preceding task:

Class 属性Properties 方法Methods
StorageCredentialsStorageCredentials
CloudStorageAccountCloudStorageAccount CreateCloudBlobClientCreateCloudBlobClient
CloudBlobClientCloudBlobClient GetContainerReferenceGetContainerReference
CloudBlobContainerCloudBlobContainer SetPermissionsAsyncSetPermissionsAsync
ListBlobsSegmentedAsyncListBlobsSegmentedAsync
BlobContinuationTokenBlobContinuationToken
BlobResultSegmentBlobResultSegment 结果Results
CloudBlockBlobCloudBlockBlob GetSharedAccessSignatureGetSharedAccessSignature
SharedAccessBlobPolicySharedAccessBlobPolicy SharedAccessStartTimeSharedAccessStartTime
SharedAccessExpiryTimeSharedAccessExpiryTime
权限Permissions

服务器端加密Server-side encryption

Azure 存储服务加密 (SSE) 可帮助你保护数据。Azure Storage Service Encryption (SSE) helps you protect and safeguard your data. SSE 加密静态数据,处理加密、解密和密钥管理。SSE encrypts data at rest, handling encryption, decryption, and key management. 采用 256 位 AES 加密所有数据,它是现在最强有力的分组密码之一。All data is encrypted using 256-bit AES encryption, one of the strongest block ciphers available.

SSE 自动加密所有性能层(标准和高级)、所有部署模型(Azure 资源管理器和经典)、所有 Azure 存储服务(Blob、队列、表和文件)中的数据。SSE automatically encrypts data in all performance tiers (Standard and Premium), all deployment models (Azure Resource Manager and Classic), and all of the Azure Storage services (Blob, Queue, Table, and File).

仅启用 HTTPSEnable HTTPS only

为了确保对存储帐户数据的请求安全,可以将请求限制为仅 HTTPS。In order to ensure that requests for data to and from a storage account are secure, you can limit requests to HTTPS only. 使用 az storage account update 命令,更新协议所需的存储帐户。Update the storage account required protocol by using the az storage account update command.

az storage account update --resource-group myresourcegroup --name <storage-account-name> --https-only true

通过使用 HTTP 协议的 curl 测试连接。Test the connection using curl using the HTTP protocol.

curl http://<storage-account-name>.blob.core.windows.net/<container>/<blob-name> -I

由于需要安全的传输,将收到以下消息:Now that secure transfer is required, you receive the following message:

HTTP/1.1 400 The account being accessed does not support http.

后续步骤Next steps

本系列教程的第三部分介绍了如何安全访问存储帐户,例如如何:In part three of the series, you learned how to secure access to the storage account, such as how to:

  • 使用 SAS 令牌访问缩略图图像Use SAS tokens to access thumbnail images
  • 启用服务器端加密Turn on server-side encryption
  • 启用仅 HTTPS 传输Enable HTTPS-only transport

本系列教程第四部分介绍如何对云存储应用程序进行监视和故障排除。Advance to part four of the series to learn how to monitor and troubleshoot a cloud storage application.