python - 使用 webapp2 session 的 Google Cloud Endpoints 身份验证

标签 python google-app-engine oauth-2.0 google-cloud-endpoints webapp2

我的 Google Cloud Endpoints API 的客户端是一个 JavaScript (AngularJS) 网络应用程序,托管在与 Endpoints API 本身相同的 Google App Engine 应用程序上。我的用户使用 webapp2 sessions 进行身份验证(数据存储)。他们不一定有 Google 帐户。我希望能够向端点 API 发出请求,例如 /api/users/me,这将返回当前登录用户的用户数据。

首先,我认为我必须为我的 App Engine 应用程序实现一个 OAuth2 提供程序,然后让 AngularJS 应用程序从我自己的 App Engine OAuth 提供程序(而不是 Google 的 OAuth 提供程序,就像内置的身份验证机制)。

然而,this comment建议不要实现我自己的 OAuth2 提供程序,而是在我的请求中(在消息字段中或在 HTTP header 中)向 Endpoints API 提供任意参数。我想该参数应该是一个用户 token (登录用户独有的一些加密值?)。然后应该将该值传递给浏览器。那不是没有安全感吗?如果可能的话,我不想在 HTTPS 上提供我的 AngularJS 应用程序(以节省成本)。

这是 OAuth2 的一个很好的用例吗?还是 OAuth2 仅用于授予第三方应用程序访问用户数据的权限?

如果 OAuth2 不是可行的方法:如何将用户 token 安全地传递给浏览器并防止中间人攻击?用户 token 是否应在一定时间后过期?

最佳答案

我刚刚完全实现了您所描述的内容。基本上这个方法可以解决问题:

def get_current_session(request_state):
    cookies = werkzeug.http.parse_cookie(request_state.headers.get('Cookie'))
    sess_cookie = cookies.get('mc_session')
    parts = sess_cookie.split('|')
    if len(parts) != 3:
        logging.error('Cookie does not have 3 parts')
        return False

    signature = hmac.new(COOKIE_SECRET_KEY, digestmod=hashlib.sha1)
    signature.update('|'.join(parts))
    sig_hex = signature.hexdigest()
    if compare_hashes(sig_hex, parts[2]):
        logging.error('Cookie signature mismatch!')
        return False

    cookie_data = webapp2_extras.json.b64decode(parts[0])
    return sessions_ndb.Session.get_by_sid(cookie_data['_sid'])

您可以使用以下 API 方法调用它:

session = get_current_session(self.request_state)

您可以在以下位置找到所有详细信息:https://blog.artooro.com/2014/08/21/share-sessions-between-google-cloud-endpoints-and-webapp2/

关于python - 使用 webapp2 session 的 Google Cloud Endpoints 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20684614/

相关文章:

c# - OAuth 2.0 与 Web API 和 Xamarin

python - 更改日期范围并循环运行

google-app-engine - Google App Engine 上的 Networkx

rest - 使用LinkedIn API中的Oauth 2.0获取用户个人资料

google-app-engine - 我想在 firebase 存储上获取我的图像的服务 url

Android 与 Google Cloud SQL 的连接

oauth - Google OAuth - 保密客户端 ID

python - Sublime text 和 Linux-KDE。系统区域设置设置为无法处理非 ASCII 字符的值

python - defaultdict constant_factory 的行为不符合预期

python - 以字符串元组作为索引的 Pandas DataFrame