'How to include Bearer Token in Header using Django Rest Framework?

I'm using rest_framework_simplejwt package for JWT authentication in Django. I created some APIs for login, reg, token_verify, referesh_token and student_data.

I restricted to view student details which are fetched from Database. So, user can't see it without authentication. Here is the image for better understanding. Student RestAPI

As you brothers can see that I pass a Bearer token in postman and then student api work. how i can do this same thing when i have to show the data on frontend? How i'm able to pass bearer token when user is generated the access token by logedin to student route for auth?

If I open the link in browser. logined

when i go on student then this happens student data page

How I can pass the access_token so i'm authenticated and see the students data? I am trying to this thing for last 10Hours here is the code.

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)
        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):
    authentication_classes=[JWTAuthentication]
    permission_classes=[IsAuthenticated]

    StudentSerializer_Class=StudentSerializer
    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
        users={
            'key':ACCESS_TOKEN_GLOBAL
        }
        return Response(
    {
        "message": "Login Successfully",
        "code": "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})

Please help me!



Solution 1:[1]

You just need to pass the bearer token with the request header. Like -> Authorization: Bearer

In angularjs we have a service ($http) which helps to add the authorization token to request header.

$http service documentation

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 Aman Giri