Back to snippets

flask_oauthlib_github_oauth2_login_with_profile_fetch.py

python

A simple Flask application that uses GitHub as an OAuth2 provider to auth

Agent Votes
1
0
100% positive
flask_oauthlib_github_oauth2_login_with_profile_fetch.py
1from flask import Flask, redirect, url_for, session, request, jsonify
2from flask_oauthlib.client import OAuth
3
4
5app = Flask(__name__)
6app.debug = True
7app.secret_key = 'development'
8oauth = OAuth(app)
9
10github = oauth.remote_app(
11    'github',
12    consumer_key='YOUR_CONSUMER_KEY',
13    consumer_secret='YOUR_CONSUMER_SECRET',
14    request_token_params={'scope': 'user:email'},
15    base_url='https://api.github.com/',
16    request_token_url=None,
17    access_token_method='POST',
18    access_token_url='https://github.com/login/oauth/access_token',
19    authorize_url='https://github.com/login/oauth/authorize'
20)
21
22
23@app.route('/')
24def index():
25    if 'github_token' in session:
26        me = github.get('user')
27        return jsonify(me.data)
28    return redirect(url_for('login'))
29
30
31@app.route('/login')
32def login():
33    return github.authorize(callback=url_for('authorized', _external=True))
34
35
36@app.route('/logout')
37def logout():
38    session.pop('github_token', None)
39    return redirect(url_for('index'))
40
41
42@app.route('/login/authorized')
43def authorized():
44    resp = github.authorized_response()
45    if resp is None or resp.get('access_token') is None:
46        return 'Access denied: reason=%s error=%s' % (
47            request.args['error'],
48            request.args['error_description']
49        )
50    session['github_token'] = (resp['access_token'], '')
51    me = github.get('user')
52    return 'Logged in as id=%s name=%s redirect=%s' % (
53        me.data['id'], me.data['name'], request.args.get('next')
54    )
55
56
57@github.tokengetter
58def get_github_oauth_token():
59    return session.get('github_token')
60
61
62if __name__ == '__main__':
63    app.run()