首页 > 解决方案 > cookie 不在浏览器 django rest 中创建

问题描述

我正在尝试通过 cookie 中的访问令牌进行授权。但是我在设置 cookie 时遇到了问题。我在登录时设置了cookie:

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)

如果我授权邮递员,一切顺利,cookie 已设置。

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

但是如果你通过前端来做,我只会得到这个

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

我的前端请求:

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

我还配置了 cors 标头CORS_ALLOW_CREDENTIALS = True

标签: pythonreactjsdjangocookiesdjango-rest-framework

解决方案


我明白这是怎么回事,cookie 在 chrome 中的 localhost 上不起作用


推荐阅读