Please see the error below I am getting when trying to send a REST API PUT call to Azure.
{"error":{"code":"AuthenticationFailed","message":"Authentication failed. The 'Authorization' header is missing."}}
Here is my code for authorization.
def authorized():
if request.args.get('state') != session.get("state"):
return redirect(url_for("index")) # No-OP. Goes back to Index page
if "error" in request.args: # Authentication/Authorization failure
return render_template("auth_error.html", result=request.args)
if request.args.get('code'):
cache = _load_cache()
result = _build_msal_app(cache=cache).acquire_token_by_authorization_code(
request.args['code'],
scopes=app_config.SCOPE, # Misspelled scope would cause an HTTP 400 error here
redirect_uri=url_for("authorized", _external=True))
if "error" in result:
return render_template("auth_error.html", result=result)
session["user"] = result.get("id_token_claims")
_save_cache(cache)
return redirect(url_for("index"))
def _load_cache():
cache = msal.SerializableTokenCache()
if session.get("token_cache"):
cache.deserialize(session["token_cache"])
return cache
def _save_cache(cache):
if cache.has_state_changed:
session["token_cache"] = cache.serialize()
def _build_msal_app(cache=None, authority=None):
return msal.ConfidentialClientApplication(
app_config.CLIENT_ID, authority=authority or app_config.AUTHORITY,
client_credential=app_config.CLIENT_SECRET, token_cache=cache)
def _build_auth_url(authority=None, scopes=None, state=None):
return _build_msal_app(authority=authority).get_authorization_request_url(
scopes or [],
state=state or str(uuid.uuid4()),
redirect_uri=url_for("authorized", _external=True))
def _get_token_from_cache(scope=None):
cache = _load_cache() # This web app maintains one cache per session
cca = _build_msal_app(cache=cache)
accounts = cca.get_accounts()
if accounts: # So all account(s) belong to the current signed-in user
result = cca.acquire_token_silent(scope, account=accounts[0])
_save_cache(cache)
return result
Here is where the code is that includes the http request.
@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']
url = f'https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourcegroup}/providers/Microsoft.Storage/storageAccounts/{name}?api-version=2019-06-01'
r = requests.put((url))
print(r.text)
return r.text
Also note I have already registered the application with Azure AD, and I've already set up my application to authenticate with Azure AD, and I can log in to the application using the Azure AD authentication. I am also receiving the token at login and it's being stored in cache.
If you want to create Azure storage account with Azure rest API, we need to call the Azure rest API with Azure AD access token. For more details, please refer to the official document and the blog
for example
REST API
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}?api-version=2019-06-01
Authorization: Bearer <access token>
content-type: application/json
{
"sku": {
"name": "Standard_GRS"
},
"kind": "Storage",
"location": "eastus"
}
python code
import json
@app.route("/storageaccountcreate")
def graphcall():
token = _get_token_from_cache(["https://management.azure.com/user_impersonation"])
if not token:
return redirect(url_for("login"))
headers={'Authorization': 'Bearer ' + token['access_token'],
'Content-Type': 'application/json'
}
payload={
"sku": {
"name": "Standard_GRS"
},
"kind": "Storage",
"location": "eastus"}
payload=json.dumps(payload)
name = request.form['storageaccountname']
resourcegroup = request.form['resourcegroup']
subscriptionId = request.form['subscriptionId']
location = request.form['location']
sku = request.form['sku']
url = f'https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourcegroup}/providers/Microsoft.Storage/storageAccounts/{name}?api-version=2019-06-01'
response = requests.request("PUT", url, headers=headers, data = payload)
print(response.text)
return response.text
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With