eltaco431
eltaco431

Reputation: 850

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?

Upvotes: 0

Views: 432

Answers (2)

Gary Liu
Gary Liu

Reputation: 13918

Only modify your token_endpoint to https Protocols. E.G: 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.

Upvotes: 1

Jack Zeng
Jack Zeng

Reputation: 2267

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

Upvotes: 1

Related Questions