我正在构建一个使用django-rest-framework
身份验证实现的rest API,django-rest-knox
并且我想将令牌存储在带有React前端的仅http cookie中。所以我使用了这个代码:
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
从这个主题django-rest-knox with cookie
此代码使用 Set-Cookie 标头并且它可以工作,但问题是当我想在受保护的路由中请求时,我需要 Authorization 标头的令牌,所以我该怎么做。