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

时间:2019-12-19 09:08:16

标签: python azure azure-devops-rest-api

在Azure Blob存储中,我需要的是在用户登录其帐户时获取访问令牌,并使用此访问令牌执行列表/上传/下载用户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打电话给get request to list时,我得到server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature。如何使用获得的令牌访问Blob存储中的文件?我们可以使用python吗?

1 个答案:

答案 0 :(得分:0)

如果要使用Azure AD访问Azure Blob存储,请参考以下步骤:

  1. 注册Azure AD应用程序

  2. 配置Azure AP复制

    a。配置权限    enter image description here    enter image description here

  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

enter image description here