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?

2
  • 1
    Did you try params=payload? Or is it meant to be a post? Commented Jun 17, 2016 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. Commented Jun 20, 2016 at 0:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.