在Cookie中设置Django REST Frmework JWT [英] Set Django REST Frmework JWT in cookies

查看:200
本文介绍了在Cookie中设置Django REST Frmework JWT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆