1

I'm having issues receiving the bearer token using Python for the Microsoft Graph API. Here is what I have so far:

import requests
import json

headers = {
'Content-Type': 'x-www-form-urlencoded',
'Authorization': 'Basic'
}

data = {
"grant_type": "client_credentials",
"client_id" :"<client_id>",
"client_secret": "<client_secret>",
"resource": "https://graph.microsoft.com"
}

r = requests.post('<token_address>', headers=headers, data=data)
print(r.text)

I have it worked in Postman, through x-www-form-urlencoded, but can't seem to get it working in Python. It returns The request body must contain the following parameter: 'grant_type'. I realize the problem probably has to do with needed the data converted, but I am not sure where to start.

1

2 Answers 2

3

You're sending some invalid headers in your request:

  • The Content-Type should be application/x-www-form-urlencoded not x-www-form-urlencoded.
  • You shouldn't be sending an Authorization header at all.

Technically, since requests.post sends data as form encoded by default, you can safely remove your headers from the request:

payload = {
    'grant_type': 'client_credentials',
    'client_id': '<client_id>',
    'client_secret': '<client_secret>',
    'resource': 'https://graph.microsoft.com',
    }
r = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=payload)
print(r.text)
Sign up to request clarification or add additional context in comments.

Comments

0

I believe that OAuth expects the body to be URL-encoded, like this:

data = "grant_type=client_credentials"
    + "&client_id=<client_id>"
    + "&client_secret=<client_secret>"
    + "&resource=https://graph.microsoft.com"

1 Comment

Unfortunately, it is still returning the same error.

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.