2

我目前正在使用 endpoints-proto-datastore 库构建 Google Cloud Endpoints 后端,并且在您请求用户时遇到了需要 apikey 的问题。用户登录后,他们会收到一个 APIkey,然后将其发回以进行连续的 put(有效),但是我如何在 GET 上要求用户名/电子邮件和 apikey?目前,如果用户这样做:

@User.method(request_fields=('id', 'apiToken',), path='users', http_method='GET', name='user.get')
def user_get(self, query):
    return query

由于 ID 正确,用户被从数据存储中拉出,并且完全忽略了 apiToken。我如何要求这两个字段?(另一方面,我如何在请求中发回用户的 ID?)

4

2 回答 2

1

我发现这样做的最简单方法是:

   @User.method(request_fields=('id', 'apiToken',), path='users', http_method='GET', name='user.get')
def user_get(self, user_model):
    user = ndb.Key('User', int(user_model.id)).get()
    if user.apiToken != user_model.apiToken:
        raise endpoints.UnauthorizedException('You are not authorized to view this data')
    return user.clean()

user_model 将存储 userId 和 apiToken ,因此我使用密钥从 ndb 中提取“真实”数据并检查 user_model 是否具有正确的令牌,如果正确则返回模型,如果不正确,我拒绝

于 2015-11-05T02:58:34.923 回答
1

如果您正在实现自己的 API 密钥方案,如您的代码所示,那么您需要自己手动检查 API 密钥是否有效。

您的示例看起来像“基本”示例中的示例,并且您已按照“ simple_get ”示例添加了参数。对于某些背景,“simple_get”示例中的文档提到“id”是 EndpointsModel 为常见操作(如按 id 检索)自动定义的五个特殊辅助属性之一。这就是为什么您的代码无需您对“id”参数执行任何“特殊”操作即可自动运行的原因。如果您尝试获取该实体,该示例仍会检查该实体是否存在:

if not my_model.from_datastore:
      raise endpoints.NotFoundException('MyModel not found.')

由于您的“apiKey”字段没有特殊的辅助属性,因此您需要在方法中添加自己的代码来检查密钥是否有效,如果无效则返回 401 或适当的错误。另一种选择是根据“ basic_with_auth ”示例也使用谷歌的一些内置身份验证。

最后,由于 endpoints-proto-datastore 只是主要端点库的语法糖,因此您需要阅读完整的文档以获取有关如何从端点方法返回值等更多信息。

于 2015-11-02T02:32:20.700 回答