Skip to content

Instantly share code, notes, and snippets.

@yongjincho
Last active April 9, 2021 02:55
Show Gist options
  • Save yongjincho/c655b6b6a0add324f462e03ea3da0f68 to your computer and use it in GitHub Desktop.
Save yongjincho/c655b6b6a0add324f462e03ea3da0f68 to your computer and use it in GitHub Desktop.
github oauth example
import requests
from flask import Flask
from flask import request, jsonify
# Register your application and paste CLIENT_ID and CLIENT_SECRET below.
# https://github.com/settings/applications/new
CLIENT_ID = 'YOUR_CLIENT_ID'
CLIENT_SECRET = 'YOUR_CLIENT_SECRET'
SCOPE = 'user'
RANDOM_STATE = 'random_state'
app = Flask(__name__)
@app.route('/')
def home():
return f'<a href="https://github.com/login/oauth/authorize?client_id={CLIENT_ID}&scope={SCOPE}&state={RANDOM_STATE}">github login</a>'
@app.route('/redirect')
def redirect():
code = request.args['code']
state = request.args['state']
assert state == RANDOM_STATE
# Give a temporary code and get the real access token
r = requests.post(
'https://github.com/login/oauth/access_token',
headers={'Accept': 'application/json'},
data={
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'code': code,
'state': RANDOM_STATE,
})
data = r.json()
access_token = data['access_token']
scope = data['scope']
print(f'access_token = {access_token}')
print(f'scope = {scope}')
# Get user information with the access token
r = requests.get(
'https://api.github.com/user',
headers={'Authorization': f'token {access_token}'})
data = r.json()
return jsonify(data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment