'How to set Authorization header in Django?

I want to set the bearer token in the authorization header. why? Because I am using rest_framework_simplejwt in my Django project. I want to implement authorization using JWT. For that, I create an access token and save it in cookies on user login.

Now I want to check if the access token which is stored in the cookie is invalid or expired? So, the user can see the data fetched from DB. Let me tell you some more detail then I will be able to tell you my problem.

when I change the token in the cookie manually and refreshed it it just shows that I am login.

Is there any best way to send this Token to the frontend by including in header or if we can update the previous Token by new Token in Login View. I am not getting that how to work with Django REST Framework default authtoken. Please guide me what is the standard process of using Token Based Authentication

view.py

ACCESS_TOKEN_GLOBAL=None
class Register(APIView):
RegisterSerializer_Class=RegisterSerializer
def get(self,request):
    return render(request, 'register.html')
def post(self,request,format=None):
    serializer=self.RegisterSerializer_Class(data=request.data)
    if serializer.is_valid():
        serializer.save()
        msg={
            'msg':"Registered Successfully"
        }
        return render(request, 'login.html',msg)
    else:
        return Response({"Message":serializer.errors,"status":status.HTTP_400_BAD_REQUEST})

class Login(APIView):
def get(self,request):
    if 'logged_in' in request.COOKIES and 'Access_Token' in request.COOKIES:
        context = {
            'Access_Token': request.COOKIES['Access_Token'],
            'logged_in': request.COOKIES.get('logged_in'),
        }
        return render(request, 'abc.html', context)
    else:
        return render(request, 'login.html')

def post(self,request,format=None):
    email = request.POST.get('email')
    password = request.POST.get('password')
    print(email,password)
    user = User.objects.filter(email=email).first()

    if user is None:
        raise AuthenticationFailed('User not found!')

    if not user.check_password(password):
        raise AuthenticationFailed('Incorrect password!')


    refresh = RefreshToken.for_user(user)
    # request.headers['Authorization']=str(refresh.access_token)
    # request.
    global ACCESS_TOKEN_GLOBAL
    ACCESS_TOKEN_GLOBAL=str(refresh.access_token)
    response=render(request,'students.html')
    response.set_cookie('Access_Token',str(refresh.access_token))
    response.set_cookie('logged_in', True)
    return response

class StudentData(APIView):
   StudentSerializer_Class=StudentSerializer
   permission_classes=[IsAuthenticated]
def get(self,request,format=None):
    token = request.COOKIES.get('jwt')
    if token!=ACCESS_TOKEN_GLOBAL:
        raise AuthenticationFailed('Unauthenticated!')
    DataObj=Student.objects.all()
    serializer=self.StudentSerializer_Class(DataObj,many=True)
    serializerData=serializer.data
    return Response({"status":status.HTTP_200_OK,"User":serializerData})

def post(self,request,format=None):
    serializer=self.StudentSerializer_Class(data=request.data)
    if serializer.is_valid():
        serializer.save()
        serializerData=serializer.data
        return Response({"status":status.HTTP_200_OK,"User":serializerData})
    else:
        return Response({"Message":serializer.errors,"status":status.HTTP_400_BAD_REQUEST})

class Logout(APIView):
def post(self,request):
    try:

        response = HttpResponseRedirect(reverse('login'))

        # deleting cookies
        response.delete_cookie('Access_Token')
        response.delete_cookie('logged_in')

        return response
    except:
        return Response({"status":status.HTTP_400_BAD_REQUEST})

here is the image I get when I go on the student route to see the data.How I can fix it?

I have the token but how I will tell the server via that access_token and show the data using HTML page rather than just pass it to postman's bearer field



Solution 1:[1]

For postman:

  1. Go under the tap 'headers'.

  2. Create a new KEY: Authorization with VALUE: Token <>

That's it, your token authorization is in the header.

You can do that in every request created in postman. I'm still looking for a way to change the header in the class-based view to add the token authorization as it is not working in the APIView.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ouflak