在Cookie中设置Django REST Frmework JWT [英] Set Django REST Frmework JWT in cookies
问题描述
我正在使用 djangorestframework-jwt 对用户进行身份验证。我已经覆盖了内置的 JSONWebTokenAPIView
以在响应中返回用户详细信息。而且我还在视图中设置cookie中的令牌。
I am using djangorestframework-jwt to authenticate users. I have overridden the builtin JSONWebTokenAPIView
to return user details in the response as well. And I am also setting the token in cookies in my view.
def post(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
user = serializer.object.get('user') or request.user
token = serializer.object.get('token')
response_data = {
'access_token': token,
'user': UserInfoSerializer(user).data
}
response = Response(response_data, status=status.HTTP_200_OK)
if api_settings.JWT_AUTH_COOKIE:
expiration = (datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA)
response.set_cookie(api_settings.JWT_AUTH_COOKIE,
response.data['access_token'],
expires=expiration,
httponly=True)
return response
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
在Django服务器上工作正常。当我使用REST可浏览的api视图验证api时,可以在cookie中看到令牌。但是我的前端(React)应用程序在localhost:3000上运行,当我从前端服务器上单击此api时,我收到了成功响应,但未在cookie中设置令牌。
It works fine on Django server. I can see the token in cookies when I verify the api using REST browseable api view. But my frontend (React) app is running on localhost:3000 and when i hit this api from my frontend server I receive the success response but token is not being set in the cookies.
我还需要设置cookie域吗?
Do I need to set the cookie domain as well?
推荐答案
我需要在前端和后端设置 withCredentials:true
。
I needed to set withCredentials: true
on frontend and backend.
通过此帖子找到了答案 Django cookie无法保存在浏览器中
Found the answer thanks to this post Django cookies are not getting saved on browser
这篇关于在Cookie中设置Django REST Frmework JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!