【发布时间】:2021-04-15 02:40:38
【问题描述】:
我将限制我的工作 rest_framework.views.APIView 继承类,只对经过身份验证的用户可见。
我做了这些修改:
- 已将
authentication_classes和permission_classes添加到我的班级:
class TestView(APIView):
authentication_classes = (OAuth2Authentication,)
permission_classes = (IsAuthenticated,)
return Response("Hey there...")
- 从 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"}
- 尝试在不设置
access_token的情况下请求视图:
curl -XGET "http://172.18.0.1:8000/api/v1/test/"
{"detail":"Authentication credentials were not provided."}
- 尝试使用
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_framework和oauth2_provider已经添加到INSTALLED_APPS了。
重要编辑:
仅当使用“客户端凭据授予”进行身份验证时才存在此问题。在下面检查我自己的答案。
【问题讨论】:
-
你是如何将令牌附加到请求中的——你也可以分享那部分吗?这是您遗漏的一个 curl 命令。
-
谢谢@Noah,添加到问题中
标签: django django-rest-framework oauth-2.0 django-oauth-toolkit