教程:使用 Windows VM 系统分配的托管标识访问 Azure 存储Tutorial: Use a Windows VM system-assigned managed identity to access Azure Storage

Azure 资源的托管标识是 Azure Active Directory 的一项功能。Managed identities for Azure resources is a feature of Azure Active Directory. 支持 Azure 资源的托管标识的每个 Azure 服务都受其自己的时间线限制。Each of the Azure services that support managed identities for Azure resources are subject to their own timeline. 在开始之前,请务必查看资源的托管标识的可用性状态以及已知问题Make sure you review the availability status of managed identities for your resource and known issues before you begin.

本教程介绍了如何使用 Windows 虚拟机 (VM) 的系统分配的托管标识来访问 Azure 存储。This tutorial shows you how to use a system-assigned managed identity for a Windows virtual machine (VM) to access Azure Storage. 学习如何:You learn how to:

  • 在存储帐户中创建 Blob 容器Create a blob container in a storage account
  • 向 Windows VM 的系统分配的托管标识授予对存储帐户的访问权限Grant your Windows VM's system-assigned managed identity access to a storage account
  • 获取访问令牌并使用它来调用 Azure 存储Get an access and use it to call Azure Storage

备注

适用于 Azure 存储的 Azure Active Directory 身份验证当前处于公共预览版。Azure Active Directory authentication for Azure Storage is in public preview.

必备条件Prerequisites

启用Enable

启用系统分配的托管标识只需单击一次即可。Enabling a system-assigned managed identity is a one-click experience. 可以在创建 VM 的过程中或在现有 VM 的属性中启用它。You can either enable it during the creation of a VM or in the properties of an existing VM.

屏幕截图显示虚拟机的“系统分配”选项卡,可以在其中打开“系统分配”状态。

若要在新 VM 上启用系统分配的托管标识,请执行以下操作:To enable a system-assigned managed identity on a new VM:

  1. 登录到 Azure 门户Sign in to Azure portal

  2. 创建启用了系统分配标识的虚拟机Create a virtual machine with system-assigned identity enabled

授予访问权限Grant access

创建存储帐户Create storage account

在本部分中,创建一个存储帐户。In this section, you create a storage account.

  1. 单击 Azure 门户左上角的“+ 创建资源”按钮 。Click the + Create a resource button found on the upper left-hand corner of the Azure portal.

  2. 单击“存储”,然后单击“存储帐户 - Blob、文件、表、队列” 。Click Storage, then Storage account - blob, file, table, queue.

  3. 在“名称” 下,输入存储帐户的名称。Under Name, enter a name for the storage account.

  4. “部署模型”和“帐户类型”应分别设置为“资源管理器”和“存储(常规用途 v1)”。 Deployment model and Account kind should be set to Resource manager and Storage (general purpose v1).

  5. 确保“订阅”和“资源组”与上一步中创建 VM 时指定的名称匹配。 Ensure the Subscription and Resource Group match the ones you specified when you created your VM in the previous step.

  6. 单击“创建”。 Click Create.

    新建存储帐户

创建 blob 容器,并将文件上传到存储帐户Create a blob container and upload a file to the storage account

文件需要 blob 存储,因此你需要创建用于存储文件的 blob 容器。Files require blob storage so you need to create a blob container in which to store the file. 然后将文件上传到新存储帐户中的 blob 容器。You then upload a file to the blob container in the new storage account.

  1. 导航回新创建的存储帐户。Navigate back to your newly created storage account.

  2. 单击“Blob 服务”下的“容器” 。Under Blob Service, click Containers.

  3. 单击页面顶部的“+ 容器” 。Click + Container on the top of the page.

  4. 在“新建容器” 下,为容器输入一个名称,在“公共访问级别” 下,保留默认值。Under New container, enter a name for the container and under Public access level keep the default value .

    创建存储容器

  5. 使用你选择的编辑器,在本地计算机上创建一个标题为 hello world.txt 的文件。Using an editor of your choice, create a file titled hello world.txt on your local machine. 打开该文件并添加文本“Hello world!Open the file and add the text (without the quotes) "Hello world! :)”(不包括引号),然后保存该文件。:)" and then save it.

  6. 通过单击容器名称并单击“上传” ,将该文件上传到新创建的容器。Upload the file to the newly created container by clicking on the container name, then Upload

  7. 在“上传 blob” 窗格中,在“文件” 下,单击文件夹图标并浏览到本地计算机上的文件 hello_world.txt,选择该文件,然后单击“上传”。 In the Upload blob pane, under Files, click the folder icon and browse to the file hello_world.txt on your local machine, select the file, then click Upload. 上传文本文件Upload text file

授予访问权限Grant access

本部分介绍如何授予 VM 访问 Azure 存储容器的权限。This section shows how to grant your VM access to an Azure Storage container. 可以使用 VM 的系统分配的托管标识检索 Azure 存储 blob 中的数据。You can use the VM's system-assigned managed identity to retrieve the data in the Azure storage blob.

  1. 导航回新创建的存储帐户。Navigate back to your newly created storage account.

  2. 单击左侧面板中的“访问控制(IAM)” 链接。Click the Access control (IAM) link in the left panel.

  3. 单击页面顶部的“+ 添加角色分配” ,为 VM 添加新的角色分配。Click + Add role assignment on top of the page to add a new role assignment for your VM.

  4. 在“角色” 下,从下拉列表中,选择“存储 Blob 数据读取器”。 Under Role, from the dropdown, select Storage Blob Data Reader.

  5. 在下一个下拉列表中,在“将访问权限分配到” 下,选择“虚拟机” 。In the next dropdown, under Assign access to, choose Virtual Machine.

  6. 接下来,确保“订阅”下拉列表中列出了正确的订阅,然后将“资源组”设置为“所有资源组”。 Next, ensure the proper subscription is listed in Subscription dropdown and then set Resource Group to All resource groups.

  7. 在“选择” 下,选择你的 VM 并单击“保存”。 Under Select, choose your VM and then click Save.

    分配权限

访问数据Access data 

Azure 存储原本就支持 Azure AD 身份验证,因此可以直接接受使用托管标识获取的访问令牌。Azure Storage natively supports Azure AD authentication, so it can directly accept access tokens obtained using a managed identity. 在某种程度上,这是将 Azure 存储与 Azure AD 集成,不同于在连接字符串中提供凭据。This is part of Azure Storage's integration with Azure AD, and is different from supplying credentials on the connection string.

下面是一个 .NET 代码示例,它使用访问令牌打开到 Azure 存储的连接,然后读取之前创建的文件的内容。Here's a .NET code example of opening a connection to Azure Storage using an access token and then reading the contents of the file you created earlier. 此代码必须在 VM 上运行才能访问 VM 的托管标识终结点。This code must run on the VM to be able to access the VM's managed identity endpoint. 使用访问令牌方法需要 .NET Framework 4.6 或更高版本。.NET Framework 4.6 or higher is required to use the access token method. 相应地替换 <URI to blob file> 的值。Replace the value of <URI to blob file> accordingly. 可以通过以下方式获取此值:在“概述”页上的“属性”下,导航到你创建并上传到 blob 存储的文件,然后复制 URLYou can obtain this value by navigating to file you created and uploaded to blob storage and copying the URL under Properties the Overview page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Web.Script.Serialization;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;

namespace StorageOAuthToken
{
    class Program
    {
        static void Main(string[] args)
        {
            //get token
            string accessToken = GetMSIToken("https://storage.azure.com/");

            //create token credential
            TokenCredential tokenCredential = new TokenCredential(accessToken);

            //create storage credentials
            StorageCredentials storageCredentials = new StorageCredentials(tokenCredential);

            Uri blobAddress = new Uri("<URI to blob file>");

            //create block blob using storage credentials
            CloudBlockBlob blob = new CloudBlockBlob(blobAddress, storageCredentials);

            //retrieve blob contents
            Console.WriteLine(blob.DownloadText());
            Console.ReadLine();
        }

        static string GetMSIToken(string resourceID)
        {
            string accessToken = string.Empty;
            // Build request to acquire MSI token
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=" + resourceID);
            request.Headers["Metadata"] = "true";
            request.Method = "GET";

            try
            {
                // Call /token endpoint
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                // Pipe response Stream to a StreamReader, and extract access token
                StreamReader streamResponse = new StreamReader(response.GetResponseStream());
                string stringResponse = streamResponse.ReadToEnd();
                JavaScriptSerializer j = new JavaScriptSerializer();
                Dictionary<string, string> list = (Dictionary<string, string>)j.Deserialize(stringResponse, typeof(Dictionary<string, string>));
                accessToken = list["access_token"];
                return accessToken;
            }
            catch (Exception e)
            {
                string errorText = String.Format("{0} \n\n{1}", e.Message, e.InnerException != null ? e.InnerException.Message : "Acquire token failed");
                return accessToken;
            }
        }
    }
}

响应包含文件内容:The response contains the contents of the file:

Hello world! :)

禁用Disable

若要在 VM 上禁用系统分配的标识,请将系统分配的标识的状态设为“关” 。To disable the system-assigned identity on your VM, set the status of the system-assigned identity to Off.

屏幕截图显示虚拟机的“系统分配”选项卡,可以在其中关闭“系统分配”状态。

后续步骤Next steps

在本教程中,你已学习了如何启用 Windows VM 的系统分配的标识以访问 Azure 存储。In this tutorial, you learned how enable a Windows VM's system-assigned identity to access Azure Storage. 若要详细了解 Azure 存储,请参阅:To learn more about Azure Storage see: