【问题标题】:Could not setup django-oauth-toolkit authentication无法设置 django-oauth-toolkit 身份验证
【发布时间】:2021-04-15 02:40:38
【问题描述】:

我将限制我的工作 rest_framework.views.APIView 继承类,只对经过身份验证的用户可见。
我做了这些修改:

  1. 已将authentication_classespermission_classes 添加到我的班级:
class TestView(APIView):
    authentication_classes = (OAuth2Authentication,)
    permission_classes = (IsAuthenticated,)

    return Response("Hey there...")
  1. 从 django-oauth-toolkit 获得 access_token:
curl -XPOST "http://172.18.0.1:8000/oauth2/token/" \
-d 'grant_type=client_credentials&client_id=MY-CLIENT-ID&client_secret=MY-CLIENT-SECRET'
{"access_token": "Haje1ZTrc7VH4rRkTbJCIkX5u83Tm6", "expires_in": 36000, "token_type": "Bearer", "scope": "read write groups"}
  1. 尝试在不设置 access_token 的情况下请求视图:
curl -XGET "http://172.18.0.1:8000/api/v1/test/"
{"detail":"Authentication credentials were not provided."}
  1. 尝试使用access_token 发出新请求:
curl -XGET "http://172.18.0.1:8000/api/v1/test/" \
-H "Authorization: Bearer Haje1ZTrc7VH4rRkTbJCIkX5u83Tm6"
{"detail":"You do not have permission to perform this action."}

我应该做更多的事情来启用 access_token 身份验证吗?

注意:我已经在环境中安装了这些库:

Django==2.2.17
djangorestframework==3.12.2
django-oauth-toolkit==1.3.3

注意2:忘了说rest_frameworkoauth2_provider已经添加到INSTALLED_APPS了。

重要编辑:
仅当使用“客户端凭据授予”进行身份验证时才存在此问题。在下面检查我自己的答案。

【问题讨论】:

  • 你是如何将令牌附加到请求中的——你也可以分享那部分吗?这是您遗漏的一个 curl 命令。
  • 谢谢@Noah,添加到问题中

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


【解决方案1】:

最后我发现OAuth2Authentication 没有通过其client_credential 对用户进行身份验证(接受用户名/密码对,grant_type=password)。所以我写了这个自定义身份验证器。希望它可以帮助其他有同样问题的人。

from oauth2_provider.contrib.rest_framework import OAuth2Authentication
from oauth2_provider.models import Application


class OAuth2ClientCredentialAuthentication(OAuth2Authentication):
    """
    OAuth2Authentication doesn't allows credentials to belong to an application (client).
    This override authenticates server-to-server requests, using client_credential authentication.
    """
    def authenticate(self, request):
        authentication = super().authenticate(request)

        if not authentication is None:
            user, access_token = authentication
            if self._grant_type_is_client_credentials(access_token):
                authentication = access_token.application.user, access_token

        return authentication

    def _grant_type_is_client_credentials(self, access_token):
        return access_token.application.authorization_grant_type == Application.GRANT_CLIENT_CREDENTIALS

【讨论】:

    【解决方案2】:

    在 Django rest 框架中尝试使用 djoser 进行身份验证

    【讨论】:

    • 这不是我的问题的答案。像这样的想法和建议最好作为 cmets 提交。顺便说一句,谢谢
    • 抱歉,我无法选择添加评论或答案。 Stackoverflow 确实
    • 没关系。当您的声望分数达到 50 时,您可以在任何地方发表评论。
    • @mahyard 我有一个很好的视频解释 djoser youtu.be/ddB83a4jKSY 它很适合我
    猜你喜欢
    • 2019-06-19
    • 2015-08-30
    • 2011-06-10
    • 1970-01-01
    • 1970-01-01
    • 2022-06-30
    • 2016-03-27
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多