检查用户是否通过django TokenAuthentication进行了身份验证 [英] Check if user is authenticated with django TokenAuthentication

查看:48
本文介绍了检查用户是否通过django TokenAuthentication进行了身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用DRF开发使用 TokenAuthentication 的REST API.这将在android应用中使用.

I'm trying to develop a REST API with DRF that uses TokenAuthentication. This will be used in an android app.

我能够验证用户身份并检索其令牌.我现在遇到的问题是以下视图:

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)

基本上,应该对用户进行身份验证才能接收数据,否则,他将收到401响应.

Basically the user should be authenticated in order to receive the data, otherwise, he will receive a 401 response.

我正在使用标头中的以下参数向正确的URL发出GET请求:

I'm making a GET request to the proper URL with the following parameters in the Header:

content-type : application/json
authorization : Token <user token>

基本上,这是我为其他拥有的 Viewset (这不是Viewset)所做的工作,并且可以正常工作.

Which is basically what I'm doing for other Viewsets (this is not a Viewset) I have - and it works.

在这种情况下,它始终以401代码发送HTTP响应(用户未通过身份验证).

In this case, it's always sending the HTTP response with 401 code (user isn't authenticated).

我无法确定问题出在我传递的Header值上,还是这不是检查用户是否已通过身份验证的正确方法.

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.

,如果我这样做:"print request.user",我得到AnonymousUser

if I do: "print request.user" i get AnonymousUser

谢谢!

已解决

根据"ABDUL NIYAS P M"的建议,我使用了APIView

As suggested by "ABDUL NIYAS P M" I used the APIView

基本上,我只是在视图中添加了 @api_view(['GET'])装饰器.

Basically, I just added the @api_view(['GET']) decorator to the View.

@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.

DRF创建令牌时,还会创建会话cookie.

When DRF creates a token, it also creates the session cookie.

return HttpResponse(json.dumps({"is_authenticated": True if request.session.get('_auth_user_id', 0) else False}),
                            content_type='application/json')

这篇关于检查用户是否通过django TokenAuthentication进行了身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆