【问题标题】:How can I require an api-token field on requests?如何在请求中要求 api-token 字段?
【发布时间】:2016-01-30 08:59:27
【问题描述】:

我目前正在使用 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?)

【问题讨论】:

    标签: python-2.7 google-app-engine google-cloud-endpoints endpoints-proto-datastore


    【解决方案1】:

    如果您按照您的代码建议实现自己的 API 密钥方案,那么您需要自己手动检查 API 密钥是否有效。

    您的示例类似于“basic”示例中的示例,并且您已按照“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”示例也使用 Google 的一些内置身份验证。

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

    【讨论】:

    • 我现在不知道如何访问 apiToken(来自请求)以与模型的令牌进行比较。如何阅读请求信息?我可能做错了,但是例如,更新,由端点原型创建的用户是数据存储中用户的副本,因此我可以将其与保存的用户进行比较。
    【解决方案2】:

    我发现最简单的方法是:

       @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 是否具有正确的令牌,如果正确则返回模型,如果不正确,我拒绝

    【讨论】:

      猜你喜欢
      • 2021-01-03
      • 1970-01-01
      • 2013-07-11
      • 2014-04-11
      • 2021-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-18
      相关资源
      最近更新 更多