What is the right way to use angular2 http requests with Django CSRF protection?

Victor K picture Victor K · Dec 28, 2015 · Viewed 11.4k times · Source

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?

Answer

David picture David · Sep 20, 2016

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:

import { ModuleWithProviders, NgModule, Optional, SkipSelf } from '@angular/core';
import { CommonModule }   from '@angular/common';
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/http';

@NgModule({
    imports: [
        CommonModule,
        HttpModule
     ],
    declarations: [ ],
    exports: [ ],
    providers: [
        {
            provide: XSRFStrategy,
            useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')
        }
    ]
})


export class CoreModule {
},