首页 > 解决方案 > Rest Framework 视图之外的 Django Rest Framework 权限

问题描述

我正在使用 Rest Framework 令牌身份验证。这意味着我无法知道用户是否在休息框架视图之外进行了身份验证,例如:(常规 django 视图)。Rest Framework 令牌身份验证是一个自定义身份验证系统,只能在 Rest Framework 视图中使用。

在正常的休息框架视图中,我可以使用以下方法限制经过身份验证的用户的端点:

class ExampleView(APIView):
    permission_classes = [IsAuthenticated]

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

但是对于常规的 django 视图,我将如何做到这一点。例如:

def someDjangoView(request):
    '''
    Note that I cannout use request.user.is_authenticated.
    It will always return false as I am using rest framework token authentication.
    Which means the request parameter should be of rest framework's and not django's built-in.
    '''
    
    content = {"detail": "Only authenticated users should access this"}
    
    return JsonResponse(content)

我陷入了一种情况,我必须知道用户是否在休息框架视图之外进行了身份验证(自定义身份验证)。

有没有办法做到这一点?

标签: djangoauthenticationdjango-rest-frameworkdjango-viewsdjango-authentication

解决方案


您可以在api_view基于函数的视图中使用装饰器来启用 D​​RF:

from rest_framework.decorators import api_view, authentication_classes


@api_view(http_method_names=['GET', 'POST'])
@authentication_classes([YourTokenAuthenticationClass])
def someDjangoView(request):
    print(request.user)
    ...
    return JsonResponse(content)

推荐阅读