Search code examples
pythondjangodjango-rest-frameworkjwtdjango-authentication

Django Rest Framework With JWT user authentication (getting anonymous user )


I am using JWT with Django to Authenticate requests from Ajax jquery . My Jquery is

$.ajax({
        url: "/customerapi/get-customer-detail/",
        type: 'GET',
        // headers: {"Token": localStorage.getItem('token')},
        beforeSend: function (xhr) {
        /* Authorization header */
        xhr.setRequestHeader("Authorization", "Token " + localStorage.getItem('token'));
        xhr.setRequestHeader("X-Mobile", "false");
         },

        success: function (res) {

        }
    });

And when I get this request on server I authenticate like this

from rest_framework.permissions import IsAuthenticated

class GetCustomerData(APIView):
    authentication_classes = (JSONWebTokenAuthentication,  )
    permission_classes = (IsAuthenticated ,)
    def get(self, request):
        try:
        Customer.objects.get(id=request.user)

here my Request.user is always anonymous. Why this this is happening?

and my middleware classes are

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

Solution

  • It should be JWT instead of Token inside header value:

    xhr.setRequestHeader("Authorization", "JWT " + localStorage.getItem('token'));