Kabiljan Tanaguzov
Kabiljan Tanaguzov

Reputation: 323

Cookies not create in browser django rest

I am trying to do authorization via access token in cookie. But i am having trouble setting cookies with react. I set cookies in login:

class ApiLoginView(APIView):
    permission_classes = [AllowAny]

    def post(self, request, ):
        password = request.data.get("password")
        email = request.data.get("email")
        user = authenticate(username=email, password=password)
        if user:
            try:
                user.auth_token.delete()
            except Exception as e:
                pass
            Token.objects.create(user=user)
            response = Response()
            response.set_cookie(key='access_token', value=user.auth_token.key, httponly=True)
            response.data = {"result": True, "token": user.auth_token.key}
            print(request.COOKIES)
            auth.info("user {} login".format(user))
            return response
        else:
            return JsonResponse({"error": "Wrong Credentials"}, status=status.HTTP_400_BAD_REQUEST)

If I auth into postman, everything goes well and the cookies are set.

print(request.COOKIES)
{'csrftoken': 'JZ1OOBZ0Ilxwo8Zt7DR0SbQ8MUMyNjiPhKYOIUQqY3OeXBEheeUoIa9MSI5S0HXG', 'access_token': 'd67ab794f8752ef02bcba5418bef2c6f87cb74f2'}

But if you do it through the frontend, I get only this

{'_ym_uid': '1612967974591822622', '_ym_d': '1614006098'}

My frontend request:

      const response = await fetch("httpS://blablabla/api/auth/login", {
        method: "POST",
        credentials: "include",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(data),
      });

I also have cors headers configured CORS_ALLOW_CREDENTIALS = True

Upvotes: 2

Views: 271

Answers (1)

Kabiljan Tanaguzov
Kabiljan Tanaguzov

Reputation: 323

I understood what was the matter, cookies do not work on localhost in chrome

Upvotes: 3

Related Questions