在 cookie 中设置 Django REST 框架 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 框架 JWT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!