gpt4 book ai didi

python - 当我尝试以客户端身份请求时,DRF 通过 403 错误响应我 [客户端凭据授予]

转载 作者:行者123 更新时间:2023-12-02 03:09:36 25 4
gpt4 key购买 nike

settings.py 文件中,我编写了以下设置:

REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'oauth2_provider.contrib.rest_framework.OAuth2Authentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
}

当我使用来自密码授予应用程序的 token 调用任何API时,它工作正常,但是当我尝试使用来自客户端凭据授予的 token 调用相同的API时 应用程序,它不起作用,并且响应 403 错误:

{ "detail": "You do not have permission to perform this action." }. 

是因为默认权限吗?我不知道我必须使用什么权限!?

最佳答案

终于解决了!问题是我使用的权限。事实上,当您使用客户端凭据授予时,IsAuthenticated权限会检查request.user,该权限为None。由于 DRF 中没有支持客户端凭据授予的权限,因此您必须使用自己的 DRF custom permission 。这是我需要和使用的:

from rest_framework.permissions import BasePermission
class IsAuthenticatedOrClientCredentialPermission(BasePermission):
def has_permission(self, request, view):
if request.auth is None:
return False
grant_type = request.auth.application.get_authorization_grant_type_display()
if request.user is None:
if grant_type == 'Client credentials':
request.user = request.auth.application.user # <-- this is because I needed to get the user either the grant is 'password' or 'client credentials'
return True
else:
return False
else:
return True

但是您可能只想拥有一个权限来检查授予类型是否为客户端凭据并授予权限,如果是这样,这就是您所需要的:

from rest_framework.permissions import BasePermission
class ClientCredentialPermission(BasePermission):
def has_permission(self, request, view):
if request.auth is None:
return False
grant_type = request.auth.application.get_authorization_grant_type_display()
if request.user is None and grant_type == 'Client credentials':
return True
else:
return False

注意:如果您想使用第二个自定义权限,请注意request.userNone,您可以获取客户端的所有者(正在向您发送请求)通过 request.auth.application.user

使用(自定义)权限:

您可以通过将自定义权限添加到适当的 View 来使用它们。 (就像使用 rest_framework.permissions 下的任何 DRF 权限一样)

基于类别的 View :

class ExampleView(APIView):
permission_classes = [ClientCredentialPermission] # <-- Add your permissions to this list

def get(self, request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)

基于功能的 View :

@api_view(['GET'])
@permission_classes([ClientCredentialPermission]) # <-- Add your permissions to this list
def example_view(request, format=None):
content = {
'status': 'request was permitted'
}
return Response(content)

关于python - 当我尝试以客户端身份请求时,DRF 通过 403 错误响应我 [客户端凭据授予],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com