Skip to content

Instantly share code, notes, and snippets.

@mattrasband
Created April 17, 2016 21:58
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattrasband/6ce03c54e941a5fd71d9a9e1722342bc to your computer and use it in GitHub Desktop.
Save mattrasband/6ce03c54e941a5fd71d9a9e1722342bc to your computer and use it in GitHub Desktop.
Google OAuth with Aiohttp
#!/usr/bin/env python3
import aiohttp
from aiohttp import web
from urllib.parse import urlencode
GOOGLE_SECRET = '<google secret>'
GOOGLE_CLIENT_ID = '<google client id>'
async def google_oauthcallback(request):
if request.GET.get('error', None):
raise web.HTTPUnauthorized(body=b'Unauthorized, denied Google Authentication')
opts = {
'code': request.GET.get('code'),
'client_id': GOOGLE_CLIENT_ID,
'client_secret': GOOGLE_SECRET,
'redirect_uri': 'http://127.0.0.1:8080/api/v1/google/callback',
'grant_type': 'authorization_code',
}
async with aiohttp.post('https://www.googleapis.com/oauth2/v4/token', data=opts) as resp:
token_info = await resp.json()
async with aiohttp.get('https://www.googleapis.com/oauth2/v2/userinfo', headers={'Authorization': 'Bearer ' + token_info['access_token']}) as resp:
guser = await resp.json()
print(guser) # given_name, family_name, email, locale, gender, picture, ...
return web.json_response(guser)
async def google_loginreq(request):
opts = {
'scope': 'email profile',
'state': 'security_token',
'redirect_uri': 'http://127.0.0.1:8080/api/v1/google/callback', # you need to register this with google
'response_type': 'code',
'client_id': GOOGLE_CLIENT_ID,
'access_type': 'offline', # Allows for refresh token
}
return web.HTTPFound('https://accounts.google.com/o/oauth2/v2/auth?' + urlencode(opts))
app = web.Application(middlewares=tuple())
app.router.add_route('*', '/', IndexView)
app.router.add_route('GET', '/api/v1/google/login', google_loginreq)
app.router.add_route('GET', '/api/v1/google/callback', google_oauthcallback)
if __name__ == '__main__':
web.run_app(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment