0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah the resource (or scope for v2 token endpoint) defines the target API of the access token. They only work against one API.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.