Question: Check if user is authenticated with django TokenAuthentication

Question

Check if user is authenticated with django TokenAuthentication

Answers 0
Added at 2017-11-08 17:11
Tags
Question

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 P M" 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':
        ...
Answers to

Check if user is authenticated with django TokenAuthentication

Source Show
◀ Wstecz