Skip to content

Instantly share code, notes, and snippets.

@HuakunShen
Last active June 19, 2021 21:28
Show Gist options
  • Save HuakunShen/ad1884ca725def49d5c17b08a519af8b to your computer and use it in GitHub Desktop.
Save HuakunShen/ad1884ca725def49d5c17b08a519af8b to your computer and use it in GitHub Desktop.
GitHub OAuth 2.0 Device Flow

GitHub OAuth 2.0 Device Flow

https://docs.github.com/en/developers/apps/building-oauth-apps/authorizing-oauth-apps#non-web-application-flow

Device Flow is for apps that cannot access a browser, such as a CLI app.

app.py is an python CLI console app that demonstrates how to do Device Flow OAuth.

To run it, you have to register a GitHub OAuth App.

Open app.py, fill in the variable names at the top (client id).

Simply run app.py and follow the instructions.

python app.py

Read every piece of code to understand how it works. It's very short.

import json
import requests
CLIENT_ID = '<Enter your OAuth App client id here>'
res = requests.post("https://github.com/login/device/code", headers={
'Accept': 'application/json'
}, data={
'client_id': CLIENT_ID,
'scope': 'user'
})
data = res.json()
print(json.dumps(data, indent=4))
print(f"User Verification Code: {data['user_code']}")
print("Go to this url https://github.com/login/device and enter the code.")
print("Press any key to continue")
input()
res = requests.post('https://github.com/login/oauth/access_token', headers={
'Accept': 'application/json'
}, data={
'client_id': CLIENT_ID,
'device_code': data['device_code'],
'grant_type': 'urn:ietf:params:oauth:grant-type:device_code'
})
print(json.dumps(res.json(), indent=4))
print("\n\nUser Info:\n")
res = requests.get(
"https://api.github.com/user", headers={'Authorization': 'token ' + res.json()['access_token']})
print(json.dumps(res.json(), indent=4) + '\n\n\n')
print(
f"check your authorization at https://github.com/settings/connections/applications/{CLIENT_ID}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment