什么是使用Django的CSRF保护angular2 http请求的正确方法? [英] What is the right way to use angular2 http requests with Django CSRF protection?
问题描述
在Angular1问题可以通过配置$ HTTP的提供商来解决。这样的:
In Angular1 the problem can be solved by configuring $http-provider. Like:
app.config(function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
});
什么是一个很好的做法做同样的Angular2?
What is a good practice to do the same in Angular2?
在Angular2用,我们需要使用类的Http http请求的工作。当然,这不是一个很好的做法,CSRF行添加到功能后每次调用。
In Angular2 to work with http requests we need to use class Http. Of course that's not a good practice to add CSRF-line to each call of post-function.
我猜Angular2我应该创建自己的类继承Angular2的HTTP类,并重新定义后的功能。它是正确的做法还是有一个更优雅的方式?
I guess in Angular2 I should create own class that inherits Angular2's Http class and redefine the post-function. Is it the right approach or is there a more elegant method?
推荐答案
解决方案Angular2不作为angular1一样容易。
您需要:
Solution for Angular2 is not as easy as for angular1. You need:
-
挑选出
csrftoken
cookie的值。
添加此值来请求与名头 X-CSRFToken
。
Add this value to request headers with name X-CSRFToken
.
我提供的这个片段:
import {Injectable, provide} from 'angular2/core';
import {BaseRequestOptions, RequestOptions} from 'angular2/http'
@Injectable()
export class ExRequestOptions extends BaseRequestOptions {
constructor() {
super();
this.headers.append('X-CSRFToken', this.getCookie('csrftoken'));
}
getCookie(name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
}
export var app = bootstrap(EnviromentComponent, [
HTTP_PROVIDERS,
provide(RequestOptions, {useClass: ExRequestOptions})
]);
这篇关于什么是使用Django的CSRF保护angular2 http请求的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!