使用获得的 oauth2 令牌访问用户的 Azure Blob 存储

Access Azure Blob storage of a user using oauth2 token obtained

在 Azure blob 存储中,我需要的是在用户登录帐户时获取访问令牌,并使用此访问令牌执行 list/upload/download 用户 blob 存储中的文件。(类似于什么我们可以在 Dropbox/Google 驱动器中做)。 使用给定的请求用户身份验证,我得到了代码,

https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize?
client_id=client_id&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&response_mode=query&scope=openid%20offline_access%20https%3A%2F%2Fstorage.azure.com%2Fuser_impersonation&state=12345

代码用于使用以下请求获取令牌

POST /{tenant}/oauth2/v2.0/token HTTP/1.1
Host: https://login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
client_id=client_id&scope=openid%20offline_access%20https%3A%2F%2Fstorage.azure.com%2Fuser_impersonation&code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...&redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F&grant_type=authorization_code&client_secret=client_secret

但是当我使用 https://account_name.blob.core.windows.net/container_name?restype=container&comp=list 调用获取列表请求时,我得到 server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature。如何使用获得的令牌访问blob存储中的文件?我们可以使用 python 来做到这一点吗?

如果您想使用 Azure AD 访问 Azure blob 存储,请参考以下步骤:

  1. 注册 Azure AD 应用程序

  2. 配置 Azure 应用程序

    一个。配置权限

  3. 为用户配置 RABC 角色

az role assignment create \
    --role "Storage Blob Data Contributor" \
    --assignee <email> \
    --scope "/subscriptions/<subscription>/resourceGroups/<resource-group>/providers/Microsoft.Storage/storageAccounts/<storage-account>
  1. 获取令牌 一种。获取代码
    https://login.microsoftonline.com/<tenant>/oauth2/v2.0/authorize?
    client_id=<>
    &response_type=code
    &redirect_uri=http://localhost:3000/
    &response_mode=query
    &scope=https://storage.azure.com/user_impersonation
    &state=12345
    
    b.获取令牌
    Post     https://login.microsoftonline.com/<>/oauth2/v2.0/token
    client_id=<>
    &scope=https://storage.azure.com/user_impersonation
    &code=OAAABAAAAiL9Kn2Z27UubvWFPbm0gLWQJVzCTE9UkP3pSx1aXxUjq3n8b2JRLk4OxVXr...
    &redirect_uri=http%3A%2F%2Flocalhost%2Fmyapp%2F
    &grant_type=authorization_code
    &client_secret=<>
    
  2. 调用 Azure blob rest api
Get https://myaccount.blob.core.windows.net/mycontainer/myblob
Headers : 
            Authorization: Bearer <>
            x-ms-version: 2019-02-02