1

I am trying to request an authorization code as documented here. I am using Python requests package to do this and have the following example code:

import requests
auth_endpoint = 'https://login.microsoftonline.com/%s/oauth2/authorize?api-version=1.0' % TENANT_ID

payload = {
    'client_id': CLIENT_ID,
    'response_type': 'code',
    'resource': APP_ID_URI,
    'redirect_uri': REPLY_URL
}
response = requests.get(url=auth_endpoint, data=payload)

However, when I run the code above, I get back HTML in the body and not the response I'm expecting. It seems like the HTML code is for a login page. When I take the formatted endpoint URI and plug it into a browser, I am able to get the auth code from the redirect URI. But, is there a way to get this from the body of the response while still using the requests package?

eltaco431
  • 740
  • 2
  • 10
  • 24
  • 1
    Did you try `params=payload`? Or is it meant to be a post? – Padraic Cunningham Jun 17 '16 at 22:15
  • Authorization Code Grant Flow requires a user interaction, which means you should construct the URL, put it into a web browser, login with user name and password, and then you can get your authorization code in the redirect URL. If you need the access token only, you don't really need to use Authorization Code Grant Flow. You can try client credentials instead of authorization code. – Jack Zeng Jun 20 '16 at 00:56

1 Answers1

1

Please use session class of requests module to implement your requirement. Please refer to the following code sample:

import requests

s = requests.Session()
USERNAME = '<username_email>'
PASSWORD = '<userpassword>'
s.auth = (USERNAME, PASSWORD)
TENANT_ID = '<tenant_id>'
# Authorize URL
authorize_url = 'https://login.microsoftonline.com/%s/oauth2/authorize' % TENANT_ID
# Token endpoint.
token_url = 'https://login.microsoftonline.com/%s/oauth2/token' % TENANT_ID

payload = { 'response_type': 'code',
            'client_id': '<tenant_id>',
            'redirect_uri': 'http://localhost',
            'authority' :'authority'
          }

response = s.get(authorize_url, params=payload ,allow_redirects=True)
print response
print response.url

Any further concern, please feel free to let me know.

Gary Liu
  • 13,758
  • 1
  • 17
  • 32