Skip to content

Instantly share code, notes, and snippets.

@jdmichaud
Last active March 15, 2024 07:47
Show Gist options
  • Save jdmichaud/e224c164efb9ef7f175541bce4068429 to your computer and use it in GitHub Desktop.
Save jdmichaud/e224c164efb9ef7f175541bce4068429 to your computer and use it in GitHub Desktop.
oauth2
# python3 -mvenv venv && source venv/bin/activate && pip install flask requests && python3 server.py
# open http://localhost:8080
import flask
import requests
app = flask.Flask(__name__)
# To create a client ID/secret for Google oauth:
# 1. Go to the Google Cloud Console,
# 2. Create a project
# 3. Go to API credentials and Create a credentials of type OAuth Client ID
# 4. Make sure the URL http://localhost:8080/oauth2callback is part of the authorized redirect list.
# CLIENT_ID = '123456789.apps.googleusercontent.com'
# Read the client secret from a file or environmental variable in a real app
# CLIENT_SECRET = 'abc123'
# This is the scope you will require to have access to. Here we only need access to the user's email.
SCOPE = 'https://www.googleapis.com/auth/userinfo.email'
# This is the callback used to deal with google authentication indirection business.
REDIRECT_URI = 'http://localhost:8080/oauth2callback'
# This is the URL used to retrieve the email at the end of the oauth exchange.
EMAIL_URI = 'https://openidconnect.googleapis.com/v1/userinfo'
# Any good ol path into your application
@app.route('/')
def index():
if 'credentials' not in flask.session:
return flask.redirect(flask.url_for('oauth2callback'))
credentials = json.loads(flask.session['credentials'])
if credentials['expires_in'] <= 0:
return flask.redirect(flask.url_for('oauth2callback'))
else:
headers = {'Authorization': 'Bearer {}'.format(credentials['access_token'])}
r = requests.get(EMAIL_URI, headers=headers)
return r.json().email
@app.route('/oauth2callback')
def oauth2callback():
if 'code' not in flask.request.args:
auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type=code'
'&client_id={}&redirect_uri={}&scope={}').format(CLIENT_ID, REDIRECT_URI, SCOPE)
return flask.redirect(auth_uri)
else:
auth_code = flask.request.args.get('code')
data = {'code': auth_code,
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'grant_type': 'authorization_code'}
r = requests.post('https://oauth2.googleapis.com/token', data=data)
flask.session['credentials'] = r.text
return flask.redirect(flask.url_for('index'))
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.debug = False
app.run(port=8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment