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

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

问题描述

我在使用mod_wsgi的Apache服务器上运行的Django,以及一个angularjs应用直接送达的Apache,而不是由Django的。我想就张贴到Django的服务器调用(运行rest_framework),但我对CSRF令牌有问题。

有什么方法来设置在服务器中的令牌没有把 {%CSRF令牌%} 作为模板的一部分(因为这些页面不是通过Django的打算) ?


  1. 我希望能够得到通过GET请求作为cookie一个CSRF令牌。

  2. 我希望能够然后进行POST请求的CSRF令牌cookie值Django的服务器。


解决方案

Django和AngularJS都有CSRF已经支持,你的一部分是非常简单的。

首先,您需要启用CSRF在Django,我相信你已经这样做了,如果没有,请按照Django的文档<一个href=\"https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/#ajax\">https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/#ajax.

现在,Django会设置一个名为 csrftoken 上的第一个GET请求Cookie,并预计自定义HTTP头 X-CSRFToken 在以后的POST / PUT / DELETE请求。

有关角,预计命名为 XSRF-TOKEN 和cookie将做POST / PUT / DELETE与 X-XSRF-TOKEN 头,所以你需要做一点点的好办法使两者去与对方:

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

添加上述两行的地方在你的js code,module.config()块是一个很好的地方。

这就是它。

注意:这是角1.1.5,旧版本可能需要不同的方法。

更新:

由于角应用不被Django的服务,为了让cookie来进行设置,角度的应用程序需要做一个GET请求首先Django的。

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.

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. I would like to be able to get a csrf token through a GET request as a cookie.
  2. I would like to be able to then make POST requests to the django server with the csrf token cookie value.

解决方案

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

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.

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.

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';

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

That's it.

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

Update:

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天全站免登陆