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

2024-02-20

In settings.py文件我已经写了这个设置:

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

当我使用令牌调用任何 API 时password grant应用程序,然后它工作正常,但是当我尝试使用来自某个应用程序的令牌调用相同的 API 时client credential grant应用程序,它不起作用并且响应 403 错误:

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

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


终于解决了!问题是permission我正在使用。事实上,IsAuthenticated权限检查request.user这是None当你使用时client credentials授予。既然没有permission用于支持clien credentialsDRF 中的补助金,您必须使用自己的DRF自定义权限 https://www.django-rest-framework.org/api-guide/permissions/#custom-permissions。这就是我需要和使用的:

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

但是您可能只想获得一个权限来检查授予类型是否为client credentials并给予许可,如果是这样,这就是您所需要的:

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

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

使用(自定义)权限:

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

基于类的视图:

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)

基于功能的视图:

@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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐