繁体   English   中英

使用 Oauth 2.0 令牌上传文件到 Azure Blob 存储

[英]Using Oauth 2.0 Token to Upload File to Azure Blob Storage

我想上传(并最终下载)一个文件到 Azure Blob 存储。 我不允许使用存储 SDK,只能使用预加载的库(也称为请求、json 等)。

到目前为止,我能够使用此方法获取令牌。 完成后,我将使用所需的标头构建另一个请求。 但是,我不断收到 401 错误。

获取Token的代码:

# Set the request url
url = f'https://login.microsoftonline.com/{tenant}/oauth2/token'

# Set the request headers
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
resource = 'https://management.azure.com/'

# Set the request body
body = {
    'grant_type': 'client_credentials',
    'client_id': client_id,
    'client_secret': client_secret,
    'resource': resource
}

# Make the POST request to the authentication endpoint
response = requests.post(url, headers=headers, data=body)

# Parse the JSON response
response_json = json.loads(response.text)

# Save to variable
oauth_token = response_json['access_token']

代码有效,并返回一个令牌。 另外,需要澄清的是,我可以使用 SDK 库上传文件(这意味着应用程序注册和权限都可以),但不能手动上传。 PUT请求到Azure Blob Storage如下:

# Code to upload file to blob storage

# Set the request url
endpoint  = f'https://{storage_account_name}.blob.core.windows.net/{container_name}/{blob_name}'

# Open the file to be uploaded
with open(blob_name, "rb") as f:
    # Get file size
    file_size = str(len(f.read()))
    # Get date
    now = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
    # Move the pointer back to the beginning of the file
    f.seek(0)
    # Set the headers for the request
    headers = {
        "Authorization": f"Bearer {oauth_token}",
        "x-ms-version":"2020-04-08",
        "Content-Length": file_size,
        "x-ms-blob-type": "BlockBlob",
        "Date": now
    }
    # Send the PUT request to upload the file
    response = requests.put(endpoint, headers=headers, data=f)

response.status_code

响应状态为 401。

任何帮助表示赞赏。

我已经尝试填写超过必填的 header 字段。 我已经删除并重新创建了应用程序注册。 仍然无法访问该资源。

对于那些可能想知道的人,我应该将资源变量指定为 https://<storage_account_name>.blob.core.windows.net。 代码现在可以工作了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM