2
\$\begingroup\$

Please review this program because I wrote something in Python for the first time. This code is to be used for device authorization in oauth2 device flow.

import requests 
import webbrowser
import time

API_ENDPOINT = "<url>"
RESPONSE_TYPE = "device_code"
GRANT_TYPE = "device"
CLIENT_ID = "<client_id>"


data = {'response_type':RESPONSE_TYPE, 
        'client_id':CLIENT_ID} 

response = requests.post(url = API_ENDPOINT, data = data) # sending post request and saving response as response object 
json_response = response.json()
print("The user_code is:%s"%json_response['user_code']) 

DEVICE_CODE = json_response['device_code']
webbrowser.open(json_response['verification_uri']) # open browser with idenity screen

data = {'grant_type':GRANT_TYPE, 
        'client_id':CLIENT_ID,
        'code': DEVICE_CODE} 

while True:
    response = requests.post(url = API_ENDPOINT, data = data) 
    if response.status_code == 200:
        json_response = response.json()
        print("The access_token is:%s"%json_response['access_token']) 
        break
    else:
        print(response.text)
        time.sleep(json_response['interval'])
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.