Sadan A.
Sadan A.

Reputation: 1107

Set Django REST Frmework JWT in cookies

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)

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.

Do I need to set the cookie domain as well?

Upvotes: 5

Views: 5572

Answers (1)

Sadan A.
Sadan A.

Reputation: 1107

I needed to set withCredentials: true on frontend and backend.

Found the answer thanks to this post Django cookies are not getting saved on browser

Upvotes: 6

Related Questions