2

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

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

I wasted a week of my life trying to understand the problem. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.