Kyle Monteagudo
Kyle Monteagudo

Reputation: 79

Python InvalidHeader error when trying to send http requests to Azure REST API

I'm trying to create an http put request to use Azure REST API to create a resource group using parameters that are created with an HTML form. When trying to send the request I receive an error that my header is invalid for the authorization header.

Here is the error I receive

Exception has occurred: InvalidHeader
Value for header {Authorization: {'access_token': 'MYACCESSTOKEN', 'token_type': 'Bearer', 'expires_in': 583}} must be of type str or bytes, not <class 'dict'>

Here is my code

@app.route('/storageaccountcreate', methods = ['POST', 'PUT'])
def storageaccountcreate():
    name = request.form['storageaccountname']
    resourcegroup = request.form['resourcegroup']
    subscriptionId = request.form['subscriptionId']
    location = request.form['location']
    sku = request.form['sku']
    headers = {"Authorization": _get_token_from_cache(app_config.SCOPE)}
    url = f'https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourcegroup}/providers/Microsoft.Storage/storageAccounts/{name}?api-version=2019-06-01'
    r = requests.put(url, headers=headers)
    print(r.text)
    return(r.text)

Upvotes: 0

Views: 2054

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136356

Basically the value of your Authorization token should be in the following format: Bearer <access-token-value> however you're passing the result of your _get_token_from_cache method and hence you're getting this error.

To fix this, please take the access_token and token_type value from this method's result and create Authorization token using the format I specified above. Something like:

token_information = _get_token_from_cache(app_config.SCOPE)
token_type = token_information['token_type']
access_token = token_information['access_token']
auth_header = token_type + " " + access_token
headers = {"Authorization": auth_header}

Upvotes: 1

Related Questions