I'm building a rest API with auth implementation using Django-rest-framework and Django-rest-knox, And in the front-end I'm using React.js. I want to store the auth token securely in the front-end and I know that the best way to do it is using httponly cookies so I've used this in my code:
from django.contrib.auth import login
from rest_framework import permissions
from rest_framework.authtoken.serializers import AuthTokenSerializer
from knox.views import LoginView as KnoxLoginView
class LoginView(KnoxLoginView):
permission_classes = (permissions.AllowAny,)
def post(self, request, format=None):
serializer = AuthTokenSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
login(request, user)
response = super(LoginView, self).post(request, format=None)
token = response.data['token']
del response.data['token']
response.set_cookie(
'auth_token',
token,
httponly=True,
samesite='strict'
)
return response
This code works perfectly so it send a Set-Cookie header and create an httponly cookie. But the problem is that if those cookies aren't accessible with JavaScript how can I access protected routes from react and axios using the Authorization header.