简体   繁体   中英

Python Requests - Azure RM API returning 200 status code but 400 in content

I have some code where I am trying to authenticate against Azure's Resource Manager REST API.

import json
import requests

tenant_id = "TENANT_ID"
app_id = "CLIENT_ID"
password = "APP_SECRET"

token_endpoint = 'http://login.microsoftonline.com/%s/oauth2/token' % tenant_id
management_uri = 'https://management.core.windows.net/'

payload = { 'grant_type': 'client_credentials',
            'client_id': app_id,
            'client_secret': password
}

auth_response = requests.post(url=token_endpoint, data=payload)
print auth_response.status_code
print auth_response.reason

This returns:

200
OK

However, when I print auth_response.content or auth_reponse.text, I get back a 400 HTML error code and an error message.

HTTP Error Code: 400
Sorry, but we’re having trouble signing you in. 
We received a bad request.

I am able to get back the correct information using PostMan, however, with the same URI and payload. I used the "Generate Code" option in Postman to export my request to a Python requests script and tried running that. But, I get the same errors.

Anybody have any idea why this is happening?

You should use HTTPS instead of HTTP for token_endpoint, and you should specify API version too. Here is what you should use.

token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token?api-version=1.0' % tenant_id

Only modify your token_endpoint to https Protocols. EG: token_endpoint = 'https://login.microsoftonline.com/%s/oauth2/token' % tenant_id . You can refer to https://msdn.microsoft.com/en-us/library/azure/dn645543.aspx for more details.

Meanwhile, you can leverage Microsoft Azure Active Directory Authentication Library (ADAL) for Python for acquire the access token in a ease.

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