I read about some of the issues related to storing jwt token in local storage that's why I am trying to store token in http-only cookie. I am using following approach.
from rest_framework.views import APIView
from rest_framework.response import Response
import jwt
from django.conf import settings
from rest_framework import status
class LoginView(APIView):
def post(self, request, format=None):
email = request.data['email']
password = request.data['password']
# dummy user authentication
if email == 'email' and password == 'password':
encoded = jwt.encode(
{'email': email}, settings.SECRET_KEY, algorithm='HS256')
response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
'user': email,
}
return response
else:
return Response({'error': 'wrong credentials'}, status=status.HTTP_401_UNAUTHORIZED)
Question 1: Is this a right approach to set httponly cookie using django rest framework?
response = Response()
response.set_cookie(key='token', value=encoded, httponly=True)
response.data = {
'user': email,
}
return response
After this every time when I am getting a request from the client (using React with axios) I am able to access the cookie using request.COOKIES['token']
in django view. Using this I can write my own function for authentication but I don't think it is a perfect approach because generally, we pass token in Authorization headers which sets the request.user
based on the token and if I use this approach I will not be unable to use postman for testing and django rest frameworks IsAuthenticated
class also looks for request.user and request.user.is_authenticated
for True value.
Question 2: How to pass the token as an Authorization header from the client if the token is stored in httponly cookie?
Please help me. I am a bit confused with the workflow of http-only cookie because generally I used to store token in local storage and it was easier to retrieve the token and pass it from the frontend.