Skip to content

Instantly share code, notes, and snippets.

Last active December 7, 2020 05:33
What would you like to do?
Authenticate with GitHub from Python using the new device auth flow
#!/usr/bin/env python3
# Implements the GitHub device auth flow described here:
from urllib.parse import parse_qs
import urllib, requests, time, webbrowser, json
client_id ='a945f87ad537bfddb109'
# Kick off the headless device auth flow on
url = ''
response =, data = {'client_id': client_id, 'scope': ''})
params = parse_qs(response.text)
YELLOW = '\033[93m'
END = '\033[0m'
print ("First copy your one-time code: " + YELLOW + params['user_code'][0] + END)
input("Then, press Enter to open %s in a browser..." % (params['verification_uri'][0]))['verification_uri'][0])
print ("Waiting for authorization...", end='', flush=True)
# Poll for the user to finish the auth flow
interval = int(params['interval'][0]) + 1
while True:
print('.', end='', flush=True)
poll_response ='',
data = {'client_id': client_id,
'device_code': params['device_code'],
'grant_type': 'urn:ietf:params:oauth:grant-type:device_code'})
poll_params = parse_qs(poll_response.text)
if 'error' in poll_params:
if 'access_token' in poll_params:
print("Got access token: " + access_token)
response = requests.get('',
headers = {'Authorization': 'token ' + access_token})
r = json.loads(response.text)
login = r['login']
print("Authenticated with GitHub as %s!" % (login))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment