【问题标题】:Using Django Scopes to distinguish between user and client使用 Django Scopes 区分用户和客户端
【发布时间】:2015-02-20 03:11:16
【问题描述】:

我正在开发一个 REST API,它由 Angular js 应用程序以及其他一些应用程序/客户端使用。我正在使用 Django REST Framework,我想使用 django-oauth-toolkit OAUTH2 进行身份验证处理。

问题: 一些 API 调用应该只能由其他应用程序/客户端调用,而不是由用户本身调用(原因:允许外部应用程序为特定用户解锁成就,但不允许用户这样做)。 我想过使用两种不同的范围:一个用于用户,一个用于那些外部应用程序/客户端,并且只允许对这些范围中的任何一个进行特定的 API 调用。这是实现我的意图的正确方法吗?如果是这样,我如何限制用户获取“外部应用程序”范围?

【问题讨论】:

  • 理论上用户不能创建自己的 API 客户端并规避这种额外的“安全”级别吗?另一种选择是检查 request.token 并确保它已附加到您网站的 API 客户端。

标签: python django oauth-2.0 django-rest-framework


【解决方案1】:

我之前通过在 DjangoRestFramework 中使用自定义 Authentication 来完成此操作

class APIKeyAuthentication(BaseAuthentication):

    def authenticate(self, request):
        """
        Check if there is an api key in the request and match it
        to the api keys we have. If it matches or is empty allow entrance.
        """
        api_key = request.META.get('HTTP_X_APIKEY', None)
        if not api_key:
            # if api key not in headers try get params
            api_key = request.GET.get("apikey", request.GET.get("api_key", None))

        if not api_key:
            # no api key in request
            raise PermissionDenied(
                detail="No API key send. Use the header \"X-APIKey\" "
                       "or the GET parameter \"apikey\""
            )


        auth_user = get_user_from_django_oauth_toolkit()

        if api_key == settings.APIKEYS["internal"]:
            request.is_internal = True

        return auth_user, None

您需要更新 settings.py 以告知 DRF 使用此身份验证

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'app.authentication.APIKeyAuthentication',
    )
}

【讨论】:

  • 谢谢,这几乎就是我想要的。但是您如何将此自定义身份验证类仅应用于我的一些 API 调用?或者您的班级如何区分应用程序或用户本身的请求?
  • 在我的示例中,有一个设置 settings.APIKEYS 列出了不同类型的静态 API 键。如果您还有每个用户的密钥,那么您需要查询您的数据存储以找出用户是谁。您可以向请求中添加尽可能多的其他属性(例如 request.is_a_real_human=Truerequest.has_blue_eyes=True),以便您的视图代码可以根据需要工作。
  • APIKey 认证是否使用令牌?
猜你喜欢
  • 2019-04-02
  • 1970-01-01
  • 2018-10-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多