简体   繁体   中英

Check if user is authenticated with django TokenAuthentication

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)

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

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>

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

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.

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

Thanks!

Solved

As suggested by "ABDUL NIYAS PM" I used the APIView

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM