[英]Check if user is authenticated with django TokenAuthentication
I'm trying to develop a REST API with DRF that uses TokenAuthentication
.我正在尝试使用使用TokenAuthentication
DRF 开发 REST API。 This will be used in an android app.这将用于 android 应用程序。
I was able to authenticate a user and retrieve it's token.我能够对用户进行身份验证并检索它的令牌。 The problem I'm having now is with the following view:我现在遇到的问题是以下观点:
@csrf_exempt
def foo(request):
if request.method == 'GET':
if request.user.is_authenticated():
...
do stuff
...
return HttpResponse(data, "application/json")
else:
return HttpResponse(status=401)
Basically the user should be authenticated in order to receive the data, otherwise, he will receive a 401 response.基本上用户应该经过身份验证才能接收数据,否则他将收到 401 响应。
I'm making a GET request to the proper URL with the following parameters in the Header:我正在使用标题中的以下参数向正确的 URL 发出 GET 请求:
content-type : application/json
authorization : Token <user token>
Which is basically what I'm doing for other Viewsets (this is not a Viewset) I have - and it works.这基本上就是我为其他视图集(这不是一个视图集)所做的工作 - 并且它有效。
In this case, it's always sending the HTTP response with 401 code (user isn't authenticated).在这种情况下,它总是发送带有 401 代码的 HTTP 响应(用户未通过身份验证)。
I can't figure out if the problem is with the Header values I'm passing or if this is not the proper way to check if the user is authenticated.我不知道问题是否出在我传递的 Header 值上,或者这是否不是检查用户是否通过身份验证的正确方法。
Edit: if I do: "print request.user" i get AnonymousUser编辑:如果我这样做:“打印 request.user”我得到 AnonymousUser
Thanks!谢谢!
Solved已解决
As suggested by "ABDUL NIYAS PM" I used the APIView正如“ABDUL NIYAS PM”所建议的,我使用了 APIView
Basically, I just added the @api_view(['GET']) decorator to the View.基本上,我只是在视图中添加了@api_view(['GET'])装饰器。
@csrf_exempt
@api_view(['GET'])
@permission_classes((IsAuthenticated, ))
def foo(request):
if request.method == 'GET':
...
An easier way to do this is by checking if the user session is existing or not.一种更简单的方法是检查用户会话是否存在。
When DRF creates a token, it also creates the session cookie.当 DRF 创建令牌时,它也会创建会话 cookie。
return HttpResponse(json.dumps({"is_authenticated": True if request.session.get('_auth_user_id', 0) else False}),
content_type='application/json')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.