【问题标题】:Django not returning CSRF TokenDjango 不返回 CSRF 令牌
【发布时间】:2014-03-19 23:10:25
【问题描述】:

我使用 C# 和 Django 实现了一个应用程序,但我的问题是,当我登录客户端时,服务器会正​​确返回所有内容、sessionid 以及除 csrf 令牌之外的所有内容。

我在 middleware_classes 的设置文件中有它。这是因为我直接通过它的ip地址访问服务器吗?

我的django登录功能

class loginMobile(GenericAPIView):
    serializer_class = loginSerializer

    def post(self, request):
        try:
            email = request.DATA.get('email')
            password = request.DATA.get('password')

            user_django = authenticate(username=email, password=password)
            login(request, user_django)

            return Response({'success': True})
        except:
            return Response({'success': False})

我的 C# 请求:

using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    // Get the response stream  
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                        if (response.Cookies != null && response.Cookies.Count != 0)
                        {
                            this.cookie_col = response.Cookies;

                            this.cookies = new List<Cookie>();
                            foreach (Cookie c in response.Cookies)
                            {
                                this.cookies.Add(c);
                                if (c.Name.Equals("csrftoken"))
                                    this.csrf_token = c.Value;
                            }
                        }
                }

在“response.cookies”中,我只得到“sessionid”而不是“csrftoken” 当我在服务器中托管应用程序时也会发生这种情况,它在我的本地机器上就像一个魅力

【问题讨论】:

  • 请注意我的 C# 应用程序有问题,它在浏览器上运行良好...
  • 我对C#一无所知,但是浏览器是否可能已经有一个csrf cookie来查看另一个页面,而您的C#应用程序只调用缺少模板标签的json(?)视图或装饰器告诉 Django 发送 cookie? stackoverflow.com/questions/20361653/… 也是如此
  • 不,不是答案...不知道我在将应用程序推送到服务器时做了什么

标签: wpf django django-csrf


【解决方案1】:

所以我想出了如何解决我的问题,

我强迫 django 像这样返回 csrf 令牌:

return Response({'success': True, 'csrf':csrf(request)})

【讨论】:

    猜你喜欢
    • 2021-07-14
    • 2013-08-11
    • 2016-08-03
    • 2012-03-25
    • 2012-01-26
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多