Django csrf 令牌 + Angularjs [英] Django csrf token + Angularjs

查看:34
本文介绍了Django csrf 令牌 + Angularjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 mod_wsgi 的 apache 服务器上运行 django,以及由 apache 直接提供服务的 angularjs 应用程序,而不是 django.我想对 django 服务器(运行 rest_framework)进行 POST 调用,但是我遇到了 csrf 令牌的问题.

I have django running on an apache server using mod_wsgi, as well as an angularjs app served directly by apache, not by django. I would like to make POST calls to the django server (running rest_framework) but I am having problems with the csrf token.

有没有办法从服务器设置令牌而不将 {% csrf token %} 作为模板的一部分(因为这些页面没有通过 django)?

Is there someway to set the token from the server without putting {% csrf token %} as part of the template (since these pages aren't going through django)?

  1. 我希望能够通过 GET 请求作为 cookie 获取 csrf 令牌.
  2. 然后我希望能够使用 csrf 令牌 cookie 值向 django 服务器发出 POST 请求.

推荐答案

Django 和 AngularJS 都已经有 CSRF 支持,你的部分很简单.

Django and AngularJS both have CSRF support already, your part is quite simple.

首先,你需要在Django中开启CSRF,相信你已经开启了,如果没有,请关注Django doc https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/#ajax.

First, you need to enable CSRF in Django, I believe you have already done so, if not, follow Django doc https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/#ajax.

现在,Django 将在第一个 GET 请求上设置一个名为 csrftoken 的 cookie,并在以后的 POST/PUT/DELETE 请求中期望一个自定义 HTTP 标头 X-CSRFToken.

Now, Django will set a cookie named csrftoken on the first GET request and expects a custom HTTP header X-CSRFToken on later POST/PUT/DELETE requests.

对于 Angular,它需要名为 XSRF-TOKEN 的 cookie 并将使用 X-XSRF-TOKEN 标头执行 POST/PUT/DELETE 请求,因此您需要执行稍微调整一下,使两者相互配合:

For Angular, it expects the cookie named XSRF-TOKEN and will do POST/PUT/DELETE requests with X-XSRF-TOKEN header, so you need to do a little bit tweak to make the two go with each other:

$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';

在你的js代码的某处添加上面两行,module.config()块是一个很好的地方.

Add above two lines somewhere in your js code, module.config() block is a good place for this.

就是这样.

注意:这适用于 angular 1.1.5,旧版本可能需要不同的方法.

NOTE: This is for angular 1.1.5, older versions might need different approach.

由于 angular 应用程序不是由 django 提供的,为了让 cookie 被设置,angular 应用程序需要先向 django 发出 GET 请求.

Since the angular app isn't served by django, in order to let the cookie to be set, angular app needs to do a GET request to django first.

这篇关于Django csrf 令牌 + Angularjs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆