使用 Azure 资源托管标识授予对 Blob 和队列数据的访问权限Authorize access to blob and queue data with managed identities for Azure resources

Azure Blob 和队列存储支持使用 Azure 资源的托管标识进行 Azure Active Directory (Azure AD) 身份验证。Azure Blob and Queue storage support Azure Active Directory (Azure AD) authentication with managed identities for Azure resources. Azure 资源的托管标识可以从 Azure 虚拟机 (VM)、函数应用、虚拟机规模集和其他服务中运行的应用程序使用 Azure AD 凭据授权对 Blob 和队列数据的访问权限。Managed identities for Azure resources can authorize access to blob and queue data using Azure AD credentials from applications running in Azure virtual machines (VMs), function apps, virtual machine scale sets, and other services. 将 Azure 资源的托管标识与 Azure AD 身份验证结合使用,可避免将凭据随在云中运行的应用程序一起存储。By using managed identities for Azure resources together with Azure AD authentication, you can avoid storing credentials with your applications that run in the cloud.

本文介绍如何使用 Azure 资源的托管标识对访问授权,以便对 Azure VM 中的 Blob 或队列数据进行访问,This article shows how to authorize access to blob or queue data from an Azure VM using managed identities for Azure Resources. 另外还介绍如何在开发环境中对代码进行测试。It also describes how to test your code in the development environment.

在 VM 上启用托管标识Enable managed identities on a VM

在使用 Azure 资源的托管标识对 VM 中 Blob 和队列的访问权限进行授权之前,必须首先在 VM 上启用针对 Azure 资源的托管标识。Before you can use managed identities for Azure Resources to authorize access to blobs and queues from your VM, you must first enable managed identities for Azure Resources on the VM. 若要了解如何为 Azure 资源启用托管标识,请参阅下述文章之一:To learn how to enable managed identities for Azure Resources, see one of these articles:

有关托管标识的详细信息,请参阅 Azure 资源的托管标识For more information about managed identities, see Managed identities for Azure resources.

使用 Azure 标识库进行身份验证Authenticate with the Azure Identity library

Azure 标识客户端库为 Azure SDK 提供 Azure Azure AD 令牌身份验证支持。The Azure Identity client library provides Azure Azure AD token authentication support for the Azure SDK. 最新版本的适用于 .NET、Java、Python 和 JavaScript 的 Azure 存储客户端库与 Azure 标识库集成,提供一种简单而安全的方法来获取用于为 Azure 存储请求进行授权的 OAuth 2.0 令牌。The latest versions of the Azure Storage client libraries for .NET, Java, Python, and JavaScript integrate with the Azure Identity library to provide a simple and secure means to acquire an OAuth 2.0 token for authorization of Azure Storage requests.

Azure 标识客户端库的优点在于,它使你可以使用相同的代码来验证你的应用程序是在开发环境中运行还是在 Azure 中运行。An advantage of the Azure Identity client library is that it enables you to use the same code to authenticate whether your application is running in the development environment or in Azure. 用于 .NET 的 Azure 标识客户端库可以对安全主体进行身份验证。The Azure Identity client library for .NET authenticates a security principal. 代码在 Azure 中运行时,安全主体是 Azure 资源的托管标识。When your code is running in Azure, the security principal is a managed identity for Azure resources. 在开发环境中,不存在托管标识,因此客户端库出于测试目的会对用户或服务主体进行身份验证。In the development environment, the managed identity does not exist, so the client library authenticates either the user or a service principal for testing purposes.

进行身份验证后,Azure 标识客户端库会获得令牌凭据。After authenticating, the Azure Identity client library gets a token credential. 然后,此令牌凭据会封装在服务客户端对象中。该对象由你创建,用于对 Azure 存储执行操作。This token credential is then encapsulated in the service client object that you create to perform operations against Azure Storage. 库会获取相应的令牌凭据,为你无缝处理这一切。The library handles this for you seamlessly by getting the appropriate token credential.

有关用于 .NET 的 Azure 标识客户端库的详细信息,请参阅用于 .NET 的 Azure 标识客户端库For more information about the Azure Identity client library for .NET, see Azure Identity client library for .NET. 有关 Azure 标识客户端库的参考文档,请参阅 Azure.Identity 命名空间For reference documentation for the Azure Identity client library, see Azure.Identity Namespace.

分配可访问数据的 Azure 角色Assign Azure roles for access to data

当 Azure AD 安全主体尝试访问 Blob 或队列数据时,该安全主体必须有资源访问权限。When an Azure AD security principal attempts to access blob or queue data, that security principal must have permissions to the resource. 不管安全主体是 Azure 中的托管标识还是在开发环境中运行代码的 Azure AD 用户帐户,都必须为安全主体分配一个 Azure 角色,由该角色授权访问 Azure 存储中的 Blob 或队列数据。Whether the security principal is a managed identity in Azure or an Azure AD user account running code in the development environment, the security principal must be assigned an Azure role that grants access to blob or queue data in Azure Storage. 若要了解如何通过 RBAC 分配权限,请参阅使用 Azure Active Directory 授权访问 Azure Blob 和队列中标题为“为访问权限分配 Azure 角色”的部分。For information about assigning permissions via RBAC, see the section titled Assign Azure roles for access rights in Authorize access to Azure blobs and queues using Azure Active Directory.

在开发环境中对用户进行身份验证Authenticate the user in the development environment

代码在开发环境中运行时,可能会自动处理身份验证,也可能需要浏览器登录才能进行身份验证,具体取决于使用哪些工具。When your code is running in the development environment, authentication may be handled automatically, or it may require a browser login, depending on which tools you're using.

其他开发工具可能会提示你通过 Web 浏览器登录。Other development tools may prompt you to login via a web browser.

在开发环境中对服务主体进行身份验证Authenticate a service principal in the development environment

如果开发环境不支持单一登录或通过 Web 浏览器登录,可以使用服务主体从开发环境进行身份验证。If your development environment does not support single sign-on or login via a web browser, then you can use a service principal to authenticate from the development environment.

创建服务主体Create the service principal

若要通过 Azure CLI 来创建服务主体并分配 Azure 角色,请调用 az ad sp create-for-rbac 命令。To create a service principal with Azure CLI and assign an Azure role, call the az ad sp create-for-rbac command. 提供要分配给新服务主体的 Azure 存储数据访问角色。Provide an Azure Storage data access role to assign to the new service principal. 此外,请提供角色分配的范围。Additionally, provide the scope for the role assignment. 若要详细了解为 Azure 存储提供的内置角色,请参阅 Azure 内置角色For more information about the built-in roles provided for Azure Storage, see Azure built-in roles.

如果没有足够的权限将角色分配给服务主体,可能需要请求帐户所有者或管理员来执行相关角色分配。If you do not have sufficient permissions to assign a role to the service principal, you may need to ask the account owner or administrator to perform the role assignment.

下面的示例使用 Azure CLI 创建新服务主体,并将帐户范围内的“存储 Blob 数据读取者”角色分配给它 The following example uses the Azure CLI to create a new service principal and assign the Storage Blob Data Reader role to it with account scope

az ad sp create-for-rbac \
    --name <service-principal> \
    --role "Storage Blob Data Reader" \
    --scopes /subscriptions/<subscription>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>

az ad sp create-for-rbac 命令返回 JSON 格式的服务主体属性列表。The az ad sp create-for-rbac command returns a list of service principal properties in JSON format. 复制这些值,以便在下一步中使用它们来创建必要的环境变量。Copy these values so that you can use them to create the necessary environment variables in the next step.

{
    "appId": "generated-app-ID",
    "displayName": "service-principal-name",
    "name": "http://service-principal-uri",
    "password": "generated-password",
    "tenant": "tenant-ID"
}

重要

传播 Azure 角色分配可能需要几分钟的时间。Azure role assignments may take a few minutes to propagate.

设置环境变量。Set environment variables

Azure 标识客户端库会在运行时读取三个环境变量中的值,以对服务主体进行身份验证。The Azure Identity client library reads values from three environment variables at runtime to authenticate the service principal. 下表介绍了为每个环境变量设置的值。The following table describes the value to set for each environment variable.

环境变量Environment variable ValueValue
AZURE_CLIENT_ID 服务主体的应用 IDThe app ID for the service principal
AZURE_TENANT_ID 服务主体的 Azure AD 租户 IDThe service principal's Azure AD tenant ID
AZURE_CLIENT_SECRET 为服务主体生成的密码The password generated for the service principal

重要

设置环境变量后,关闭并重新打开控制台窗口。After you set the environment variables, close and re-open your console window. 如果使用的是 Visual Studio 或其他开发环境,则可能需要重新启动开发环境以便环境能够注册新的环境变量。If you are using Visual Studio or another development environment, you may need to restart the development environment in order for it to register the new environment variables.

有关详细信息,请参阅在门户中创建 Azure 应用标识For more information, see Create identity for Azure app in portal.

安装客户端库包Install client library packages

备注

本文中的示例使用 Azure 存储客户端库版本 12。The examples shown here use the Azure Storage client library version 12. 版本 12 的客户端库是 Azure SDK 的一部分。The version 12 client library is part of the Azure SDK. 有关 Azure SDK 的更多信息,请参阅 GitHub 上的 Azure SDK 存储库。For more information about the Azure SDK, see the Azure SDK repository on GitHub.

若要安装 Blob 存储包,请在 NuGet 包管理器控制台中运行以下命令:To install the Blob storage package, run the following command from the NuGet package manager console:

Install-Package Azure.Storage.Blobs

本文中的示例还使用用于 .NET 的 Azure 标识客户端库的最新版通过 Azure AD 凭据进行身份验证。The examples shown here also use the latest version of the Azure Identity client library for .NET to authenticate with Azure AD credentials. 若要安装包,请在 NuGet 包管理器控制台中运行以下命令:To install the package, run the following command from the NuGet package manager console:

Install-Package Azure.Identity

.NET 代码示例:创建块 Blob.NET code example: Create a block blob

向代码添加以下 using 指令,以便使用 Azure 标识和 Azure 存储客户端库。Add the following using directives to your code to use the Azure Identity and Azure Storage client libraries.

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

若要获取令牌凭据,以便代码用它来授权对 Azure 存储的请求,请创建 DefaultAzureCredential 类的实例。To get a token credential that your code can use to authorize requests to Azure Storage, create an instance of the DefaultAzureCredential class. 以下代码示例演示了如何获取经身份验证的令牌凭据并使用它来创建服务客户端对象,然后使用服务客户端来上传新的 Blob:The following code example shows how to get the authenticated token credential and use it to create a service client object, then use the service client to upload a new blob:

async static Task CreateBlockBlobAsync(string accountName, string containerName, string blobName)
{
    // 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.
        string blobContents = "This is a block blob.";
        byte[] byteArray = Encoding.ASCII.GetBytes(blobContents);

        using (MemoryStream stream = new MemoryStream(byteArray))
        {
            await containerClient.UploadBlobAsync(blobName, stream);
        }
    }
    catch (RequestFailedException e)
    {
        Console.WriteLine(e.Message);
        Console.ReadLine();
        throw;
    }
}

备注

若要使用 Azure AD 授权针对 Blob 或队列数据的请求,必须对这些请求使用 HTTPS。To authorize requests against blob or queue data with Azure AD, you must use HTTPS for those requests.

后续步骤Next steps