Abubakar Shafique
Abubakar Shafique

Reputation: 81

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!

Upvotes: 1

Views: 7758

Answers (2)

TylerDotPy
TylerDotPy

Reputation: 11

So the above answers are generally right to a degree, in your case you are using username and password authentication, then setting a JWT for persistence across services, endpoints and routes.

Then you are trying to access your BrowsableAPI , but the jwt is not set.

One of the biggest Issues I see in your StudentData view is the fact that you are checking for the cookie : 'jwt', with this line below:

token = request.COOKIES.get('jwt')

However in your login view you are setting the cookie header to :

response.set_cookie('Access_Token',str(refresh.access_token))

You should look into creating user sessions on login , this way you can remove that global variable:

https://docs.djangoproject.com/en/4.1/topics/http/sessions/

if you use sessions and set the access token, when a user or you logs into the browsable api and/or the login page, their session will now contain the auth token (jwt) that you can set.

Then make sure in your endpoints that you are verifying the jwt payload and that it matches to the user sending the request. This should fix your issues, the browsable api is generally only for development any way I strongly recommend changing your settings.py

If you are in debug mode you should use the browsableAPI if you are in production you should use the json renderer backend.

Now when you go to check your requests, the browsableAPI has a login section, you need to login in this panel before you will be able to navigate your api properly.

Without the session objects you will need to use Js in order to append the headers to each request to your backend, however with sessions the cookie is stored to the users session and the endpoint will be able to get the session during the request to check for the cookie.

Upvotes: 0

Aman Giri
Aman Giri

Reputation: 11

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

Upvotes: 1

Related Questions