教程:使用 Linux VM 系统分配的标识通过 SAS 凭据访问 Azure 存储Tutorial: Use a Linux VM system-assigned identity to access Azure Storage via a SAS credential

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.

本教程介绍如何使用系统分配的托管标识为 Linux 虚拟机 (VM) 获取存储共享访问签名 (SAS) 凭据。This tutorial shows you how to use a system-assigned managed identity for a Linux virtual machine (VM) to obtain a storage Shared Access Signature (SAS) credential. 具体而言,是服务 SAS 凭据Specifically, a Service SAS credential.

Note

本教程中生成的 SAS 密钥不会受 VM 限制/绑定到 VM。The SAS key generated in this tutorial will not be restricted/bound to the VM.

服务 SAS 提供了在不公开帐户访问密钥的情况下授权特定的服务(在我们的示例中为 blob 服务)在有限时间内访问存储帐户中对象的权限。A Service SAS provides the ability to grant limited access to objects in a storage account, for a limited time and a specific service (in our case, the blob service), without exposing an account access key. 可以像平常在执行存储操作时一样使用 SAS 凭据,例如使用存储 SDK 时。You can use a SAS credential as usual when doing storage operations, for example when using the Storage SDK. 对于本教程,我们将演示使用 Azure 存储 CLI 上传和下载 blob。For this tutorial, we demonstrate uploading and downloading a blob using Azure Storage CLI. 将了解如何执行以下操作:You will learn how to:

  • 创建存储帐户Create a storage account
  • 在存储帐户中创建 Blob 容器Create a blob container in the storage account
  • 向 VM 授予对资源管理器中的存储帐户 SAS 的访问权限Grant your VM access to a storage account SAS in Resource Manager
  • 使用 VM 的标识获取一个访问令牌,并使用它从资源管理器检索 SASGet an access token using your VM's identity, and use it to retrieve the SAS from Resource Manager

先决条件Prerequisites

创建存储帐户Create a storage account

如果还没有存储帐户,现在将创建存储帐户。If you don't already have one, you will now create a storage account. 也可以跳过此步骤,并向 VM 的系统分配的托管标识授予对现有存储帐户密钥的访问权限。You can also skip this step and grant your VM system-assigned managed identity access to the keys of an existing storage account.

  1. 单击 Azure 门户左上角的“+/创建新服务”按钮。 Click the +/Create new service button found on the upper left-hand corner of the Azure portal.

  2. 依次单击“存储” 、“存储帐户” ,并将显示新的“创建存储帐户”面板。Click Storage, then Storage Account, and a new "Create storage account" panel will display.

  3. 输入存储帐户的名称,稍后将使用该名称。Enter a Name for the storage account, which you will use later.

  4. “部署模型”和“帐户类型”应分别设置为“资源管理器”和“通用”。 Deployment model and Account kind should be set to "Resource manager" and "General purpose", respectively.

  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 in the storage account

稍后我们会将文件上传并下载到新存储帐户。Later we will upload and download a file to the new storage account. 由于文件需要 blob 存储,我们需要创建用于存储文件的 blob 容器。Because files require blob storage, we need to create a blob container in which to store the file.

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

  2. 在左侧面板上,单击“Blob 服务”下的“容器”链接。 Click the Containers link in the left panel, under "Blob service."

  3. 单击页面顶部的“+ 容器” ,将滑出“新建容器”面板。Click + Container on the top of the page, and a "New container" panel slides out.

  4. 为容器指定名称,选择访问级别,单击“确定” 。Give the container a name, select an access level, then click OK. 在本教程中的后面部分将使用所指定的名称。The name you specified will be used later in the tutorial.

    创建存储容器

授权 VM 的系统分配的托管标识使用存储 SASGrant your VM's system-assigned managed identity access to use a storage SAS

Azure 存储原本不支持 Azure AD 身份验证。Azure Storage does not natively support Azure AD authentication. 但是,可以使用 VM 的系统分配的托管标识从资源管理器检索存储 SAS,然后使用 SAS 来访问存储。However, you can use your VM's system-assigned managed identity to retrieve a storage SAS from the Resource Manager, then use the SAS to access storage. 在此步骤中,将向 VM 的系统分配的托管标识授予对存储帐户 SAS 的访问权限。In this step, you grant your VM's system-assigned managed identity access to your storage account SAS.

  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. 在页面左侧,将“角色” 设置为“存储帐户参与者”。Set Role to "Storage Account Contributor", on the right side of the page.

  5. 在下一个下拉列表中,把“将访问权限分配给” 设置为资源“虚拟机”。In the next dropdown, set Assign access to the resource "Virtual Machine".

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

  7. 最后,在“选择”下,从下拉列表中选择你的 Linux 虚拟机,然后单击“保存”。 Finally, under Select choose your Linux Virtual Machine in the dropdown, then click Save.

    Alt 图像文本

使用 VM 标识获取访问令牌,并使用它调用 Azure 资源管理器Get an access token using the VM's identity and use it to call Azure Resource Manager

在本教程的剩余部分中,我们从先前创建的 VM 入手。For the remainder of the tutorial, we will work from the VM we created earlier.

若要完成这些步骤,需要使用 SSH 客户端。To complete these steps, you will need an SSH client. 如果使用的是 Windows,可以在适用于 Linux 的 Windows 子系统中使用 SSH 客户端。If you are using Windows, you can use the SSH client in the Windows Subsystem for Linux. 如果需要有关配置 SSH 客户端密钥的帮助,请参阅如何在 Azure 上将 SSH 密钥与 Windows 配合使用如何创建和使用适用于 Azure 中 Linux VM 的 SSH 公钥和私钥对If you need assistance configuring your SSH client's keys, see How to Use SSH keys with Windows on Azure, or How to create and use an SSH public and private key pair for Linux VMs in Azure.

  1. 在 Azure 门户中,导航到“虚拟机” ,转到 Linux 虚拟机,然后在“概述” 页中单击顶部的“连接” 。In the Azure portal, navigate to Virtual Machines, go to your Linux virtual machine, then from the Overview page click Connect at the top. 复制用于连接到 VM 的字符串。Copy the string to connect to your VM.

  2. 使用 SSH 客户端连接到 VM。Connect to your VM using your SSH client.

  3. 接下来,将提示你输入创建“Linux VM” 时添加的“密码” 。Next, you will be prompted to enter in your Password you added when creating the Linux VM. 然后应可以成功登录。You should then be successfully signed in.

  4. 使用 CURL 获取 Azure 资源管理器的访问令牌。Use CURL to get an access token for Azure Resource Manager.

    下面是用于获取访问令牌的 CURL 请求和响应:The CURL request and response for the access token is below:

    curl 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https%3A%2F%2Fmanagement.chinacloudapi.cn%2F' -H Metadata:true    
    

    Note

    在上面的请求中,“resource”参数的值必须与 Azure AD 预期的值完全一致。In the previous request, the value of the "resource" parameter must be an exact match for what is expected by Azure AD. 如果使用 Azure 资源管理器资源 ID,必须在 URI 的结尾添加斜线。When using the Azure Resource Manager resource ID, you must include the trailing slash on the URI. 在下面的响应中,为简洁起见,已缩短了 access_token 元素。In the following response, the access_token element as been shortened for brevity.

    {"access_token":"eyJ0eXAiOiJ...",
    "refresh_token":"",
    "expires_in":"3599",
    "expires_on":"1504130527",
    "not_before":"1504126627",
    "resource":"https://management.chinacloudapi.cn",
    "token_type":"Bearer"} 
    

从 Azure 资源管理器中获取 SAS 凭据,以便调用存储Get a SAS credential from Azure Resource Manager to make storage calls

现在,使用在上一部分中检索到的访问令牌通过 CURL 调用资源管理器,来创建存储 SAS 凭据。Now use CURL to call Resource Manager using the access token we retrieved in the previous section, to create a storage SAS credential. 获取 SAS 凭据后,便可以调用存储上传/下载操作。Once we have the SAS credential, we can call storage upload/download operations.

对于此请求,我们将使用以下 HTTP 请求参数来创建 SAS 凭据:For this request we'll use the follow HTTP request parameters to create the SAS credential:

{
    "canonicalizedResource":"/blob/<STORAGE ACCOUNT NAME>/<CONTAINER NAME>",
    "signedResource":"c",              // The kind of resource accessible with the SAS, in this case a container (c).
    "signedPermission":"rcw",          // Permissions for this SAS, in this case (r)ead, (c)reate, and (w)rite.  Order is important.
    "signedProtocol":"https",          // Require the SAS be used on https protocol.
    "signedExpiry":"<EXPIRATION TIME>" // UTC expiration time for SAS in ISO 8601 format, for example 2017-09-22T00:06:00Z.
}

这些参数包括在针对 SAS 凭据的请求的 POST 正文中。These parameters are included in the POST body of the request for the SAS credential. 有关用于创建 SAS 凭据的参数的详细信息,请参阅 List Service SAS REST reference(列出服务 SAS REST 参考)。For more information on the parameters for creating a SAS credential, see the List Service SAS REST reference.

使用以下 CURL 请求来获取 SAS 凭据。Use the following CURL request to get the SAS credential. 请务必将 <SUBSCRIPTION ID><RESOURCE GROUP><STORAGE ACCOUNT NAME><CONTAINER NAME><EXPIRATION TIME> 参数值替换为你自己的值。Be sure to replace the <SUBSCRIPTION ID>, <RESOURCE GROUP>, <STORAGE ACCOUNT NAME>, <CONTAINER NAME>, and <EXPIRATION TIME> parameter values with your own values. <ACCESS TOKEN> 值替换为前面检索的访问令牌:Replace the <ACCESS TOKEN> value with the access token you retrieved earlier:

curl https://management.chinacloudapi.cn/subscriptions/<SUBSCRIPTION ID>/resourceGroups/<RESOURCE GROUP>/providers/Microsoft.Storage/storageAccounts/<STORAGE ACCOUNT NAME>/listServiceSas/?api-version=2017-06-01 -X POST -d "{\"canonicalizedResource\":\"/blob/<STORAGE ACCOUNT NAME>/<CONTAINER NAME>\",\"signedResource\":\"c\",\"signedPermission\":\"rcw\",\"signedProtocol\":\"https\",\"signedExpiry\":\"<EXPIRATION TIME>\"}" -H "Authorization: Bearer <ACCESS TOKEN>"

Note

上述 URL 中的文本区分大小写,因此如果对资源组使用了大小写格式,请务必在 URL 中相应地体现出来。The text in the prior URL is case sensitive, so ensure if you are using upper-lowercase for your Resource Groups to reflect it accordingly. 此外必须知道,这是 POST 请求,而不是 GET 请求。Additionally, it’s important to know that this is a POST request not a GET request.

CURL 响应返回 SAS 凭据:The CURL response returns the SAS credential:

{"serviceSasToken":"sv=2015-04-05&sr=c&spr=https&st=2017-09-22T00%3A10%3A00Z&se=2017-09-22T02%3A00%3A00Z&sp=rcw&sig=QcVwljccgWcNMbe9roAJbD8J5oEkYoq%2F0cUPlgriBn0%3D"} 

创建要上传到 blob 存储容器的示例 blob 文件。Create a sample blob file to upload to your blob storage container. 在 Linux VM 上,可使用以下命令执行该操作。On a Linux VM you can do this with the following command.

echo "This is a test file." > test.txt

接下来,运行 CLI az storage 命令使用 SAS 凭据进行身份验证,并将文件上传到 blob 容器。Next, authenticate with the CLI az storage command using the SAS credential, and upload the file to the blob container. 对于此步骤,需要在 VM 上安装最新的 Azure CLI(如果尚未安装)。For this step, you will need to install the latest Azure CLI on your VM, if you haven't already.

 az storage blob upload --container-name 
                        --file 
                        --name
                        --account-name 
                        --sas-token

响应:Response:

Finished[#############################################################]  100.0000%
{
  "etag": "\"0x8D4F9929765C139\"",
  "lastModified": "2017-09-21T03:58:56+00:00"
}

此外,可以使用 Azure CLI 下载文件,并使用 SAS 凭据对其进行身份验证。Additionally, you can download the file using the Azure CLI and authenticating with the SAS credential.

请求:Request:

az storage blob download --container-name
                         --file 
                         --name 
                         --account-name
                         --sas-token

响应:Response:

{
  "content": null,
  "metadata": {},
  "name": "testblob",
  "properties": {
    "appendBlobCommittedBlockCount": null,
    "blobType": "BlockBlob",
    "contentLength": 16,
    "contentRange": "bytes 0-15/16",
    "contentSettings": {
      "cacheControl": null,
      "contentDisposition": null,
      "contentEncoding": null,
      "contentLanguage": null,
      "contentMd5": "Aryr///Rb+D8JQ8IytleDA==",
      "contentType": "text/plain"
    },
    "copy": {
      "completionTime": null,
      "id": null,
      "progress": null,
      "source": null,
      "status": null,
      "statusDescription": null
    },
    "etag": "\"0x8D4F9929765C139\"",
    "lastModified": "2017-09-21T03:58:56+00:00",
    "lease": {
      "duration": null,
      "state": "available",
      "status": "unlocked"
    },
    "pageBlobSequenceNumber": null,
    "serverEncrypted": false
  },
  "snapshot": null
}

后续步骤Next steps

在本教程中,你已学习了如何使用 Linux VM 系统分配的托管标识通过 SAS 凭据来访问 Azure 存储。In this tutorial, you learned how to use a Linux VM system-assigned managed identity to access Azure Storage using a SAS credential. 若要深入了解 Azure 存储 SAS,请参阅:To learn more about Azure Storage SAS see: