注销登录新用户后 Django csrf 失败

Django csrf fails after logout login new user

即使我理解了这个问题,我也不确定如何解决这个问题。我有一个支持 django 的 api,它有一个端点,可以让用户更改电子邮件。如果登录用户 A 输入了 已经存在的 电子邮件,它会检查登录用户 A 输入的密码是否与已经存在的用户 B 对象(即他拥有另一个旧帐户)相对应。如果是这样,我必须注销实际用户 A 并重新登录已经存在的 B 帐户。​​

...
if User.objects.filter(email=email).exists():
    # If the email already belongs to another account
    user = authenticate(username=email, password=password)
    if user is not None:
        # The user is the owner of the existing account, he has the password
        # Get already existing client object
        client_existing_user_obj = Client.objects.get(user=user)

        # get clients actual cart
        actual_cart = client.cart
        # update existing clients cart with newly created cart
        client_existing_user_obj.cart = actual_cart

        # logout user with the old email, login already existing user
        logout(request)
        login(request, user)

        ...

端点正常工作,它 returns 200。但是,下一个 post & put 请求回答 403 - "detail": "CSRF Failed: CSRF token missing or incorrect."

我该如何解决这个问题?任何建议都会有所帮助。

Django rotates the CSRF token 当用户登录时。这是一项安全措施。

在提交更多 POST/PUT 请求之前,您必须在登录后刷新令牌(例如通过刷新页面)。