Skip to content

Instantly share code, notes, and snippets.

@jayme-github
Created October 17, 2016 06:17
Show Gist options
  • Select an option

  • Save jayme-github/138316675f29981e1e00a2e1ef78b345 to your computer and use it in GitHub Desktop.

Select an option

Save jayme-github/138316675f29981e1e00a2e1ef78b345 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import jwt
import logging
from requests_oauthlib import OAuth2Session
os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1' # For testing only
LOGFMT = '%(asctime)s (%(name)s.%(funcName)s) [%(levelname)s] %(message)s'
logging.basicConfig(format=LOGFMT, level=logging.DEBUG)
'''
* Log into Azure Management Portal <https://manage.windowsazure.com>
* Go to Active Directory -> Applications and click ADD at the bottom
* Select Add an application my organization is developing
* Name (SomeName), select WEB APPLICATION AND/OR WEB API
* Enter a redirect URL (e.g. http://localhost:10080/; does not need to be reachable and can be changed later)
* Enter a Microsoft endpoint URL for APP ID (e.g. https://mycorp.onmicrosoft.com/Somename; doesn't really matter, we wont use it, just have to be unique)
* Go to the Configuration page for the Application you just added
* Take note of the CLIENT ID that will be used as the client_id below
* Create a new key by selecting a duration anddaving the form. Make sure to copy down the value generated immediately as you will not be able to access it after leaving the page. This key will be the client_secret below
* Ensure that under permissions to other applications, the required "Microsoft Graph" permission are selected (depends on which ressources you want to access
* Add a REPLY URL (e.g. http://localhost:10080/; does not need to be reachable and can be changed later)
* Save your changes, then click the VIEW ENDPOINTS button at the bottom
'''
client_id = ''
client_secret = ''
tenant_id = 'common'
redirect_uri = 'http://localhost:10080/' # Needs to match the REDIRECT URL you've used above
resource_id = 'https://graph.microsoft.com'
auth_endpoint = 'https://login.microsoftonline.com/common/oauth2/authorize'
token_endpoint = 'https://login.microsoftonline.com/common/oauth2/token'
oauth = OAuth2Session(client_id, redirect_uri=redirect_uri)
authorization_url, state = oauth.authorization_url(auth_endpoint)
print('Please go to %s and authorize access.' % authorization_url)
authorization_response = raw_input('Enter the full callback URL: ')
token = oauth.fetch_token(
token_endpoint,
authorization_response=authorization_response,
resource=resource_id,
client_secret=client_secret
)
token_data = jwt.decode(token.get('access_token'), None, False)
oauth.get('https://graph.microsoft.com/v1.0/...')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment