John Hugery
John Hugery

Reputation: 11

Authorization issues with MS Graph

So I have been using powershell for quite a while now and am somewhat familiar with getting a token from an Azure application using MS Graph configured with application API permissions. I am now attempting to perform the same in a python console application and am getting flummoxed as I constantly get a 400 error. here's the snippet of my code...

import requests
import json
app_id='<appid>'
client_secret='<client secret>'
token_url='https://login.microsoftonline.com/<tenant id>/oauth2    /v2.0/token'
token_data = {
 'grant_type': 'client_credentials',
 'client_id': app_id,
 'client_secret': client_secret,
 'resource': 'https://graph.microsoft.com',
 'scope':'https://graph.microsoft.com/.default'
}
headers = {'content-type':'application/json'}
token_r = requests.post(token_url, json=token_data)
token = token_r.json().get('access_token')

any ideas?

Upvotes: 0

Views: 205

Answers (1)

John Hugery
John Hugery

Reputation: 11

Figured it out. I needed to add the oAuth2 requests library. See sample code below:

    import requests
    import json
    from requests_oauthlib import OAuth2Session
    from oauthlib.oauth2 import BackendApplicationClient
    app_id='<app id>'
    client_secret='<client Secret>'
    token_url='https://login.microsoftonline.com/tennantname.onmicrosoft.com/oauth2/v2.0/token'
    scope='https://graph.microsoft.com/.default'
    client = BackendApplicationClient(client_id=app_id, scope=scope, grant_type="client_credentials")
    session = OAuth2Session(client=client, scope=scope)
    # fill access token
    token = session.fetch_token(token_url=token_url,client_id=app_id,scope=scope,client_secret=client_secret)

Upvotes: 1

Related Questions