Reputation: 318
I'm building a rest API using django-rest-framework
with auth implementation with django-rest-knox
and I want to store the token in an http only cookie with a React frontend. So I've used thie 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
from this topic django-rest-knox with cookies
This code use the Set-Cookie Header and it works but the problem is when I want to request in a protected route I need the token for the Authorization header, so how can I do it.
Upvotes: 2
Views: 420