简体   繁体   中英

Using Oauth 2.0 Token to Upload File to Azure Blob Storage

I want to upload (and eventually, download) a file to Azure Blob Storage. I am not allowed to use the Storage SDK, and can only use preloaded libraries (aka requests, json, etc).

So far, I am able to get the token using this method. Once that is done, I build another requests with the required headers. However, I keep getting a 401 Error.

Code to get 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']

Code works, and return a token. Also, to clarify, I am able to upload a file using the SDK library (which means the app registration and permissions are fine), but not manually. PUT request to Azure Blob Storage is as follows:

# 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

Response Status is 401.

Any help is appreciated.

I've tried filling in more than the required header fields. I've deleted and recreated the app registration. Still unable to access the resource.

For those that might be wondering, I should have specified the resource variable as https://<storage_account_name>.blob.core.windows.net. Code now works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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