Obtaining Azure Access Token by Python for using Microsoft Graph API


It is a Python program only to get the access token required to use the Microsoft Graph API. For the credential information required in advance, I obtained it by referring to this article.

Execution environment

macOS Big Sur 11.1 python 3.8.3

Definition of credential information

The credential information obtained in advance is defined in .zshenv.

#Definition for getting AzureAccessToken
export TENANT_ID=zzzzzzzzzzzzzzzzzzzzzzzzzz
export CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxx
export CLIENT_KEY=yyyyyyyyyyyyyyyyyyyyyyyyy

Execution program


import json
import os
import requests
import argparse
import time

#Get Microsoft GraphAPI credential information
TENANT_ID = os.environ['TENANT_ID']
CLIENT_ID = os.environ['CLIENT_ID']
CLIENT_KEY = os.environ['CLIENT_KEY']

#Obtaining an access token for Azure access
def get_azure_access_token() -> str:
    # access_Header information to get token
    headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'

    payload = {
        'client_id': CLIENT_ID,
        'scope': 'https://graph.microsoft.com/.default',
        'grant_type': 'client_credentials',
        'client_secret': CLIENT_KEY

    # access_Generate URL to get token
    TokenGet_URL = "https://login.microsoftonline.com/" + \
        TENANT_ID + "/oauth2/v2.0/token"
    # print(TokenGet_URL)

    response = requests.get(
    #Close requrest process

    #Get the result
    jsonObj = json.loads(response.text)
    return jsonObj["access_token"]

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Obtaining an access token for Azure access')
    args = parser.parse_args()

    start = time.time()
    access_token = get_azure_access_token()
    generate_time = time.time() - start

    print("Acquisition time:{0}".format(generate_time) + " [sec]")
    print("Obtained access token:")

Program execution

Let's get help first.

$ python GetAzureAccessToken.py -h
usage: GetAzureAccessToken.py [-h]

Obtaining an access token for Azure access

optional arguments:
  -h, --help  show this help message and exit

Now, let's get an access token.

$ python GetAzureAccessToken.py   

Acquisition time:0.2260270118713379 [sec]
Obtained access token:
iJKV1QiLCJub25jZSI6ImRx ・ ・ ・ Omitted ・ ・ ・ KjjJQGdwR-5CusZ0Nc0ON62Z0Jm

Reference information

I referred to the following information. I am very grateful to you.

Let's use the Microsoft Graph API. --Preparation- Let's use the Microsoft Graph API. --Practice- How to get the URL of a specific record in a specific list of a specific site in SharePoint in Python I checked the Microsoft Graph API for some reason

Recommended Posts

Obtaining Azure Access Token by Python for using Microsoft Graph API
Get an access token for the Pocket API
Speech file recognition by Google Speech API v2 using Python
Access google spreadsheet using python on raspberry pi (for myself)
[LINE Messaging API] Issue channel access token v2.1 in Python
[Python] Introduction to graph creation using coronavirus data [For beginners]
EXE Web API by Python
Azure Functions: Try Durable Functions for Python
Data acquisition using python googlemap api
[Python3] Google translate google translate without using api
Try using Pleasant's API (python / FastAPI)
OS determination by Makefile using Python
Notes for me python csv graph
[TouchDesigner] Tips for for statements using python
Try using Python argparse's action API
Excel graph creation using python xlwings
[Python] Reasons for overriding using super ()
Run Ansible from Python using API
[Python] Multiplication table using for statement
Access spreadsheets using OAuth 2.0 from Python
Access the Twitter API in Python
Google API access token and refresh token