保存 Google OAuth2 WebServerFlow 的用户名
我在Python中实现了谷歌的OAuth2认证流程(可以参考这个链接了解如何使用OAuth2WebServerFlow: https://developers.google.com/api-client-library/python/guide/aaa_oauth),但是我不知道怎么获取正在认证的用户是谁,也就是他们的邮箱地址是什么?否则,当我保存他们的OAuth2凭证时,我就不知道这些凭证是属于谁的。在auth_uri、flow或credentials对象中都没有提供认证用户的邮箱地址。我代码中的倒数第二行打印出一个JSON,里面包含了OAuth2Credentials类的键(http://google-api-python-client.googlecode.com/hg/docs/epy/oauth2client.client.OAuth2Credentials-class.html)
有没有什么好主意?我真不想直接问认证用户他们的账户信息...
我正在使用新的GMail API构建一个应用,需要离线访问用户的账户。
class Auth(app.basic.BaseHandler):
def get(self):
flow = OAuth2WebServerFlow(client_id=settings.get('google_client_id'),
client_secret=settings.get('google_client_secret'),
scope=OAUTH_SCOPE,
redirect_uri='http://localhost:8001/auth/google/return')
auth_uri = flow.step1_get_authorize_url()
return self.redirect(auth_uri)
class AuthReturn(app.basic.BaseHandler):
def get(self):
oauth_code = self.get_argument('code', '')
flow = OAuth2WebServerFlow(client_id=settings.get('google_client_id'),
client_secret=settings.get('google_client_secret'),
scope=OAUTH_SCOPE,
redirect_uri='http://localhost:8001/auth/google/return')
credentials = flow.step2_exchange(oauth_code)
# Save credentials to database. How do I get the username?
print credentials.to_json()
return self.redirect('/')
1 个回答
1
解决方案就在你请求的范围内。我定义了一个 OAUTH_SCOPE 变量,内容是:
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.modify'
但是这个范围只提供了 GMail API 定义的信息,并不包括用户的个人资料信息。所以为了扩展你的凭证能获取的信息,你需要扩大认证请求的范围:
OAUTH_SCOPE = ('https://www.googleapis.com/auth/gmail.modify '
'https://www.googleapis.com/auth/userinfo.email '
'https://www.googleapis.com/auth/userinfo.profile')
使用这个范围变量运行完全相同的代码,就能访问到 userinfo.email 和其他相关信息,这些都是我所需要的。请注意,范围参数是用空格分隔的字符串。这其实非常简洁优雅!