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';
});
What is a good practice to do the same in Angular2?
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.
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?
Currently, I solve anything with custom headers using a wrapper service around the Http Service. You can add whatever header manually and inject additional services for storing/retrieving values. This strategy also works for JWTs, for example. Have a look at the code below, I hope it helps.
Victor K had the solution, I'll just add this comment here as to what I did:
I created the component "ExRequestOptions" as Victor K said, but I also added a method "appendHeaders" to that component:
Then I had this in my main.ts:
I'm not sure the bootstrapping had any effect, so i also did this where I would post data:
Now that Angular 2 is released the following seems to be the correct way of doing this, by using
CookieXSRFStrategy
.I've configured my application to have a core module but you can do the same in your main application module instead:
I struggled with this for a few days. The advice in this article is good, but as of August, 2017 is deprecated (https://github.com/angular/angular/pull/18906). The angular2 recommended approach is simple, but has a caveat.
The recommend approach is to use HttpClientXsrfModule and to configure it to recognize django's default csrf protection. According to the django docs, django will send the cookie
csrftoken
and expect the client to return the headerX-CSRFToken
. In angular2, add the following to yourapp.module.ts
The caveat is that angular2's XSRF Protection only applies to mutating requests:
If you need to support an API that performs mutation on GET/HEAD, you will need to create your own custom interceptor. You can find an example and a discussion of the issue here.
For later versions of angular you cannot call functions in decorators. You have to use a factory provider:
And then use the factory:
Otherwise the compiler will tell you off. What I have also seen is that ng build --watch will not report this error until you kick it off again.
Victor K's answer is perfectly valid however as of angular 2.0.0-rc.2, a preferred approach would be to use CookieXSRFStrategy as below,