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.
macOS Big Sur 11.1 python 3.8.3
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
GetAzureAccessToken.py
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)
    #Run
    response = requests.get(
        TokenGet_URL,
        headers=headers,
        data=payload
    )
    #Close requrest process
    response.close
    #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("")
    print("Acquisition time:{0}".format(generate_time) + " [sec]")
    print("Obtained access token:")
    print(access_token)
    print("")
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
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