我正在使用Rest令牌身份验证。这意味着我无法知道用户是否在rest框架视图之外进行身份验证,例如:(普通django视图)。Rest令牌身份验证是一个定制的auth系统,只能在rest框架视图中使用。
在普通rest框架视图中,我可以通过以下方法限制通过身份验证的用户的端点:
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)在这种情况下,我不得不知道用户是否在rest框架视图之外通过身份验证(定制auth)。
有什么办法吗?
发布于 2021-07-27 11:56:31
可以在基于功能的视图中使用api_view装饰器来启用DRF:
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)发布于 2021-07-27 11:58:44
DRF构建在builtin Django用户auth系统之上。因此,对于常规django视图,可以使用regular methods provided by contrib.auth。
DRF还支持基于会话的身份验证(通常在使用contrib.auth时是默认的)。例如,当用户会话在浏览器中运行一些JavaScript代码时,这是非常理想的。
注意,我不能使用request.user.is_authenticated。它将始终返回false,因为我使用的是rest框架令牌身份验证。
如果使用rest框架令牌身份验证,则必须使用与此兼容的视图。request.user.is_authenticated是构建在django中的contrib.auth系统的一部分。但是,必须对用户进行身份验证,才能使其成为True。Rest Framework为您做了这件事。如果您没有使用rest框架,您必须亲自访问用户!
一个简单的答案可能是装饰您的视图,使它们利用您定义的rest框架身份验证:
@api_view(['GET'])
@authentication_classes(...) # if defaults are not applied
@permission_classes(...) # to apply permissions you need
def view(request):
return Response({"message": "Hello for today! See you tomorrow!"})https://stackoverflow.com/questions/68543363
复制相似问题