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

后端 未结 7 761
独厮守ぢ
独厮守ぢ 2020-11-28 13:23

In Angular1 the problem can be solved by configuring $http-provider. Like:

app.config(function($httpProvider) {
  $httpProvider.defaults.xsrfCookieName = \'c         


        
7条回答
  •  执笔经年
    2020-11-28 13:58

    Solution for Angular2 is not as easy as for angular1. You need:

    1. Pick out csrftoken cookie value.

    2. Add this value to request headers with name X-CSRFToken.

    I offer this snippet:

    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})
    ]);
    

提交回复
热议问题