django rest auth returns AnonymousUser


I am using django, drf and django-rest-auth. I send token from frontend in request header

    {'Authorization': 'Token {$Token}'}

But this request seems like unauthorized. I want to get users information like:

    def get_user_info(request):
        user = request.user

but it returns me AnonymousUser





        'UNICODE_JSON': True,
        'PAGE_SIZE': 0

That’s my request headers:

    POST /auth/check/ HTTP/1.1
    Host: localhost:8000
    Connection: keep-alive
    Content-Length: 0
    Pragma: no-cache
    Cache-Control: no-cache
    Authorization: Token 7d2ee4481ea0e12bd88f46d57e2e6dab3354d4b7
    Origin: http://localhost:8080
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
    Content-Type: application/json;charset=utf-8
    Accept: application/json, text/plain, */*
    Referer: http://localhost:8080/
    Accept-Encoding: gzip, deflate, br
    Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4

And full server response with headers

    HTTP/1.1 401 Unauthorized
    Date: Thu, 29 Jun 2017 05:28:06 GMT
    Server: WSGIServer/0.2 CPython/3.4.4
    Access-Control-Allow-Origin: http://localhost:8080
    Vary: Origin, Cookie
    Content-Type: application/json
    X-Frame-Options: SAMEORIGIN
    Transfer-Encoding: chunked

    {"message": "Unauthenticated"}

My view function:

    def check_auth(request):
        if request.method == 'POST':
            if request.user.is_authenticated():
                content = {'message': 'Authenticated'}
                response = JsonResponse(content, status = 200)
                return response
                content = {'message': 'Unauthenticated'}
                response = JsonResponse(content, status=401)
                return response
Asked By: Farid



You are not using Django-rest-framework in right way. Change your view like this

class CheckAuth(generics.GenericAPIView):

    def post(self, request):
        if request.user.is_authenticated():
             content = {'message': 'Authenticated'}
             return Response(content, status=200)
             content = {'message': 'Unauthenticated'}
             return Response(content, status=401)

You can further see Django-rest docs about views here.

Answered By: Muhammad Hassan

For my case i had to add @api_view(['POST']) at the begging of the function

def send_message(request):
    if request.user.is_authenticated:
Answered By: Mert Doe

Check where you gave authentication classes and check for the
the authentication you used on views and mentioned on are the same

In my case, I have used token authentication in and given basic authentication in

Answered By: Akhil