我有一个 GAE Python 应用程序,我正在将其从使用 App Engine 用户库转换为使用 oauth2client 的 oauth2。
我读到了一些有关在 App Engine 中使用 oauth2 的问题(例如 Managing users authentication in Google App Engine ),并且用户库似乎不了解是否使用任何其他身份验证系统(即 oauth2)来对用户进行身份验证。
所以我计划使用 oauth2 而不是用户库来手动滚动我的登录/注销模型。然而,我随后惊讶地发现,当使用 oauth2client.appengine 库时,对 users 库的调用返回来自 oauth2 经过身份验证的用户的数据,如以下示例代码所示:
import webapp2
from google.appengine.api import users
from oauth2client.appengine import OAuth2Decorator
oauth2deco = OAuth2Decorator(...)
class TestOauth(webapp2.RequestHandler):
@oauth2deco.oauth_required
def get(self):
print users.get_current_user() # Prints user's email
app = webapp2.WSGIApplication([
('/', TestOauth),
(oauth2deco.callback_path, oauth2deco.callback_handler())
])
在上面的示例中,系统会提示用户使用 oauth2 登录屏幕(而不是来自 users.CreateLoginURL 的传统 App Engine 登录屏幕)登录,而是调用 users.get_current_user( )按预期工作。
我很好奇,这是如何工作的?我看到 users.get_current_user() 函数返回一个新的 User() 对象,它似乎读取了一些环境变量: https://cloud.google.com/appengine/docs/standard/python/refdocs/modules/google/appengine/api/users#User
但是,我从未见过这些是由 oauth2client 设置的,所以我仍然很困惑。
最佳答案
查看 oauth2client 客户端库的 source code对于 @oauth2deco.oauth_required 装饰器,库内部似乎正在使用 Users API 来执行身份验证:
if not user:
request_handler.redirect(users.create_login_url(
request_handler.request.uri))
return
此装饰器在 oauth2client.contrib.appengine 包中定义,该实用程序可让您更轻松地在 Google App Engine 上使用 OAuth 2.0。
关于google-app-engine - oauth2client 如何与 AppEngine 用户库 (GAE Python) 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49266887/