教程:从 Web 应用访问 Azure 存储Tutorial: Access Azure Storage from a web app

了解如何使用托管标识为 Azure 应用服务上运行的 Web 应用(不是登录用户)访问 Azure 存储。Learn how to access Azure Storage for a web app (not a signed-in user) running on Azure App Service by using managed identities.

关系图展示如何访问存储。

你要从 Web 应用添加对 Azure 数据平面(Azure 存储、Azure SQL 数据库、Azure Key Vault 或其他服务)的访问权限。You want to add access to the Azure data plane (Azure Storage, Azure SQL Database, Azure Key Vault, or other services) from your web app. 你可以使用共享密钥,但之后需要考虑操作安全性:谁可以创建、部署和管理机密。You could use a shared key, but then you have to worry about operational security of who can create, deploy, and manage the secret. 还可能会将此密钥签入 GitHub,黑客知道如何扫描它。It's also possible that the key could be checked into GitHub, which hackers know how to scan for. 向 Web 应用授予数据访问权限的更安全方法是使用托管标识A safer way to give your web app access to data is to use managed identities.

Azure Active Directory (Azure AD) 中的托管标识允许应用程序服务通过基于角色的访问控制 (RBAC) 访问资源,而不要求使用应用凭据。A managed identity from Azure Active Directory (Azure AD) allows App Service to access resources through role-based access control (RBAC), without requiring app credentials. 向 Web 应用分配托管标识之后,Azure 会负责创建和分发证书。After assigning a managed identity to your web app, Azure takes care of the creation and distribution of a certificate. 用户无需费心管理机密或应用凭据。People don't have to worry about managing secrets or app credentials.

在本教程中,你将了解:In this tutorial, you learn how to:

  • 在 Web 应用上创建系统分配的托管标识。Create a system-assigned managed identity on a web app.
  • 创建存储帐户和 Azure Blob 存储容器。Create a storage account and an Azure Blob Storage container.
  • 使用托管标识从 Web 应用访问存储。Access storage from a web app by using managed identities.

如果没有 Azure 试用版订阅,请在开始前创建一个试用版订阅If you don't have an Azure trail subscription, create a trial subscription before you begin.

先决条件Prerequisites

在应用上启用托管标识Enable managed identity on an app

如果通过 Visual Studio 创建和发布 Web 应用,则已在应用上启用了托管标识。If you create and publish your web app through Visual Studio, the managed identity was enabled on your app for you. 在应用服务中,在左侧窗格中选择“标识”,然后选择“系统分配” 。In your app service, select Identity in the left pane, and then select System assigned. 验证“状态”是否设置为“打开” 。Verify that the Status is set to On. 如果不是,请依次选择“保存”和“是”以启用系统分配的托管标识 。If not, select Save and then select Yes to enable the system-assigned managed identity. 启用托管标识后,状态将设置为“启用”并且对象 ID 可用。When the managed identity is enabled, the status is set to On and the object ID is available.

屏幕截图中显示“系统分配的标识”选项。

此步骤创建一个新的对象 ID,该 ID 不同于在“身份验证/授权”窗格中创建的应用 ID。This step creates a new object ID, different than the app ID created in the Authentication/Authorization pane. 复制系统分配的托管标识的对象 ID。Copy the object ID of the system-assigned managed identity. 稍后需要用到此信息。You'll need it later.

创建存储帐户和 Blob 存储容器Create a storage account and Blob Storage container

现在可以创建存储帐户和 Blob 存储容器。Now you're ready to create a storage account and Blob Storage container.

每个存储帐户都必须属于 Azure 资源组。Every storage account must belong to an Azure resource group. 资源组是对 Azure 资源进行分组的逻辑容器。A resource group is a logical container for grouping your Azure services. 创建存储帐户时,可以选择创建新的资源组,或者使用现有的资源组。When you create a storage account, you have the option to either create a new resource group or use an existing resource group. 本文介绍如何创建新资源组。This article shows how to create a new resource group.

可以使用常规用途 v2 存储帐户访问所有 Azure 存储服务:Blob、文件、队列、表和磁盘。A general-purpose v2 storage account provides access to all of the Azure Storage services: blobs, files, queues, tables, and disks. 本文所述的步骤将创建常规用途 v2 存储帐户,但创建任何类型的存储帐户的步骤都相似。The steps outlined here create a general-purpose v2 storage account, but the steps to create any type of storage account are similar.

Azure 存储中的 Blob 已组织成容器。Blobs in Azure Storage are organized into containers. 你需要先创建容器,然后才能在本教程的稍后部分上传 Blob。Before you can upload a blob later in this tutorial, you must first create a container.

若要在 Azure 门户中创建常规用途 v2 存储帐户,请执行以下步骤。To create a general-purpose v2 storage account in the Azure portal, follow these steps.

  1. 在 Azure 门户菜单中,选择“所有服务” 。On the Azure portal menu, select All services. 在资源列表中输入“存储帐户”。In the list of resources, enter Storage Accounts. 开始键入时,会根据输入筛选该列表。As you begin typing, the list filters based on your input. 选择“存储帐户” 。Select Storage Accounts.

  2. 在显示的“存储帐户”窗口中,选择“添加” 。In the Storage Accounts window that appears, select Add.

  3. 选择要在其中创建存储帐户的订阅。Select the subscription in which to create the storage account.

  4. 在“资源组”字段下,从下拉菜单中选择包含你的 Web 应用的资源组。Under the Resource group field, select the resource group that contains your web app from the drop-down menu.

  5. 然后,输入存储帐户的名称。Next, enter a name for your storage account. 所选名称在 Azure 中必须唯一。The name you choose must be unique across Azure. 该名称还必须为 3 到 24 个字符,并且只能包含数字和小写字母。The name also must be between 3 and 24 characters in length and can include numbers and lowercase letters only.

  6. 选择存储帐户的位置或使用默认位置。Select a location for your storage account, or use the default location.

  7. 将这些字段设置为其默认值:Leave these fields set to their default values:

    字段Field ValueValue
    部署模型Deployment model Resource ManagerResource Manager
    性能Performance 标准Standard
    帐户类型Account kind StorageV2(常规用途 v2)StorageV2 (general-purpose v2)
    复制Replication 读取访问异地冗余存储 (RA-GRS)Read-access geo-redundant storage (RA-GRS)
    访问层Access tier Hot
  8. 选择“查看+创建”可查看存储帐户设置并创建帐户。Select Review + Create to review your storage account settings and create the account.

  9. 选择“创建” 。Select Create.

若要在 Azure 存储中创建 Blob 存储容器,请执行以下步骤。To create a Blob Storage container in Azure Storage, follow these steps.

  1. 转到 Azure 门户中的新存储帐户。Go to your new storage account in the Azure portal.

  2. 在存储帐户的左侧菜单中滚动到“Blob 服务”部分,然后选择“容器” 。In the left menu for the storage account, scroll to the Blob service section, and then select Containers.

  3. 选择“+ 容器”。 Select the + Container button.

  4. 键入新容器的名称。Type a name for your new container. 容器名称必须小写,必须以字母或数字开头,并且只能包含字母、数字和短划线 (-) 字符。The container name must be lowercase, must start with a letter or number, and can include only letters, numbers, and the dash (-) character.

  5. 设置容器的公共访问权限级别。Set the level of public access to the container. 默认级别为“专用(禁止匿名访问)”。 The default level is Private (no anonymous access).

  6. 选择“确定” 创建容器。Select OK to create the container.

授予对存储帐户的访问权限Grant access to the storage account

你需要先向 Web 应用授予对存储帐户的访问权限,然后才能创建、读取或删除 Blob。You need to grant your web app access to the storage account before you can create, read, or delete blobs. 在上一步骤中,你使用托管标识配置了在应用服务上运行的 Web 应用。In a previous step, you configured the web app running on App Service with a managed identity. 使用 Azure RBAC,可以向托管标识授予对其他资源的访问权限,这一点与所有安全主体一样。Using Azure RBAC, you can give the managed identity access to another resource, just like any security principal. “存储 Blob 数据参与者”角色向 Web 应用(由系统分配的托管标识表示)授予对 Blob 容器和数据的读取、写入和删除访问权限。The Storage Blob Data Contributor role gives the web app (represented by the system-assigned managed identity) read, write, and delete access to the blob container and data.

Azure 门户中,进入你的存储帐户,向 Web 应用授予访问权限。In the Azure portal, go into your storage account to grant your web app access. 依次选择左侧窗格中的“访问控制(IAM)”、“角色分配” 。Select Access control (IAM) in the left pane, and then select Role assignments. 你将看到有权访问存储帐户的用户的列表。You'll see a list of who has access to the storage account. 现在,你要向机器人(需要访问存储帐户的应用服务)添加角色分配。Now you want to add a role assignment to a robot, the app service that needs access to the storage account. 选择“添加” > “添加角色分配”。Select Add > Add role assignment.

在“角色”中,选择“存储 Blob 数据参与者”,授予 Web 应用读取存储 Blob 的权限 。In Role, select Storage Blob Data Contributor to give your web app access to read storage blobs. 在“分配访问权限到”中,选择“应用服务” 。In Assign access to, select App Service. 在“订阅”中,选择你的订阅。In Subscription, select your subscription. 然后选择你想要授予其访问权限的应用服务。Then select the app service you want to provide access to. 选择“保存”。Select Save.

屏幕截图中显示“添加角色分配”屏幕。

Web 应用现在可以访问存储帐户。Your web app now has access to your storage account.

访问 Blob 存储 (.NET)Access Blob Storage (.NET)

DefaultAzureCredential 类用于获取代码的令牌凭据,以授权对 Azure 存储的请求。The DefaultAzureCredential class is used to get a token credential for your code to authorize requests to Azure Storage. 创建 DefaultAzureCredential 类的实例,该类使用托管标识提取令牌并将其附加到服务客户端。Create an instance of the DefaultAzureCredential class, which uses the managed identity to fetch tokens and attach them to the service client. 下面的代码示例获取经过身份验证的令牌凭据,并使用它创建服务客户端对象,该对象将上传新的 Blob。The following code example gets the authenticated token credential and uses it to create a service client object, which uploads a new blob.

若要查看作为示例应用程序一部分的代码,请参阅 GitHub 上的示例To see this code as part of a sample application, see the sample on GitHub.

安装客户端库包Install client library packages

安装 Blob 存储 NuGet 包以便与 Blob 存储一起使用,并安装适用于 .NET NuGet 包的 Azure 标识客户端库来使用 Azure AD 凭据进行身份验证。Install the Blob Storage NuGet package to work with Blob Storage and the Azure Identity client library for .NET NuGet package to authenticate with Azure AD credentials. 使用 .NET Core 命令行接口或 Visual Studio 中的包管理器控制台,在项目中安装客户端库。Install the client libraries by using the .NET Core command-line interface or the Package Manager Console in Visual Studio.

打开一个命令行,并切换到包含项目文件的目录。Open a command line, and switch to the directory that contains your project file.

运行安装命令。Run the install commands.

dotnet add package Azure.Storage.Blobs

dotnet add package Azure.Identity

示例Example

using System;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using System.IO;
using Azure.Identity;

// Some code omitted for brevity.

static public async Task UploadBlob(string accountName, string containerName, string blobName, string blobContents)
{
    // Construct the blob container endpoint from the arguments.
    string containerEndpoint = string.Format("https://{0}.blob.core.chinacloudapi.cn/{1}",
                                                accountName,
                                                containerName);

    // Get a credential and create a client object for the blob container.
    BlobContainerClient containerClient = new BlobContainerClient(new Uri(containerEndpoint),
                                                                    new DefaultAzureCredential());

    try
    {
        // Create the container if it does not exist.
        await containerClient.CreateIfNotExistsAsync();

        // Upload text to a new block blob.
        byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);

        using (MemoryStream stream = new MemoryStream(byteArray))
        {
            await containerClient.UploadBlobAsync(blobName, stream);
        }
    }
    catch (Exception e)
    {
        throw e;
    }
}

清理资源Clean up resources

如果已完成本教程,并且不再需要 Web 应用或相关资源,请清理创建的资源If you're finished with this tutorial and no longer need the web app or associated resources, clean up the resources you created.

后续步骤Next steps

在本教程中,你将了解:In this tutorial, you learned how to:

  • 创建系统分配的托管标识。Create a system-assigned managed identity.
  • 创建存储帐户和 Blob 存储容器。Create a storage account and Blob Storage container.
  • 使用托管标识从 Web 应用访问存储。Access storage from a web app by using managed identities.