0

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

]

1 Answer 1

2

It should be JWT instead of Token inside header value:

xhr.setRequestHeader("Authorization", "JWT " + localStorage.getItem('token'));
Sign up to request clarification or add additional context in comments.

2 Comments

thanks sir <3 . working on localhost now but returning anon user on live . when I checked header on live by doing request.headers['Authorization'] it gives 'Request' object has no attribute 'headers'
Even request.META['HTTP_AUTHORIZATION'], is not carrying my header. Do you have any clue what can be issue ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.