[Django]-How to create a POST request (including CSRF token) using Django and AngularJS

7πŸ‘

βœ…

Can’t you make a call like this:

$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})

The data can be whatever you wish to pass and then just append &{{csrf_token}} to that.

In your resource params:{}, try adding csrfmiddlewaretoken:{{csrf_token}} inside the params

Edit:

You can pass data to the request body as

item.$update({csrfmiddlewaretoken:{{csrf_token}}})

and to headers as

var csrf = '{{ csrf_token }}'; 
update:{method:'POST', headers: {'X-CSRFToken' : csrf }} 

It is an undocumented issue

40πŸ‘

I know this is more than 1 year old, but if someone stumbles upon the same issue, angular JS already has a CSRF cookie fetching mechanism (versions of AngularJS starting at 1.1.5), and you just have to tell angular what is the name of the cookie that django uses, and also the HTTP header that it should use to communicate with the server.

Use module configuration for that:

var app = angular.module('yourApp');
app.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);

Now every request will have the correct django CSRF token. In my opinion this is much more correct than manually placing the token on every request, because it uses built-in systems from both frameworks (django and angularJS).

πŸ‘€Anoyz

1πŸ‘

In recent angularjs version giving solution is not working . So i tried the following

  • First add django tag {% csrf_token %} in the markup.

  • Add a $http inspector in your app config file

angular.module('myApp').config(function ( $httpProvider) {
   $httpProvider.interceptors.push('myHttpRequestInterceptor'); 
});
  • Then define that myHttpRequestInterceptor
angular.module("myApp").factory('myHttpRequestInterceptor', function ( ) {

   return {
             config.headers = { 
              'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() } 
             } 
   return config; 
  }}; 
});

it’ll add the X-CSRFToken in all angular request

And lastly you need to add the Django middleware ” django.middleware.csrf.CsrfViewMiddleware'”
It’ll solve the CSRF issue

0πŸ‘

var app = angular.module('angularFoo', ....

app.config(["$httpProvider", function(provider) {
  provider.defaults.headers.common['X-CSRFToken'] = '<<csrftoken value from template or cookie>>';
}])
πŸ‘€Serge K.

0πŸ‘

I use this:

In Django view:

@csrf_protect
def index(request):
    #Set cstf-token cookie for rendered template
    return render_to_response('index.html', RequestContext(request))

In App.js:

(function(A) {
    "use strict";
    A.module('DesktopApplication', 'ngCookies' ]).config(function($interpolateProvider, $resourceProvider) {
        //I use {$ and $} as Angular directives
        $interpolateProvider.startSymbol('{$');
        $interpolateProvider.endSymbol('$}');
        //Without this Django not processed urls without trailing slash
        $resourceProvider.defaults.stripTrailingSlashes = false; 
    }).run(function($http, $cookies) {
        //Set csrf-kookie for every request
        $http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
        $http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    });
}(this.angular));

For sending correct request you must convert object to param-form:

$http.post('/items/add/', $.param({name: 'Foo'}));//Here $ is jQuery

0πŸ‘

I have checked in Angular 15 and Django 4.0 now can fetch csrf-token. Here is solution (is working):

  1. In services file add function
authorizeUser(username: string, password: string, csrfmiddlewaretoken: string): Observable<any>{
  const url = 'http://localhost:8000/admin/login/?next=/admin/'
  const encodedBody = new URLSearchParams();
  encodedBody.set('username', username);
  encodedBody.set('password', password);
  encodedBody.set('csrfmiddlewaretoken', csrfmiddlewaretoken)

  return this.http.post(url, encodedBody);

}
  1. Add component AdminComponent
export class AdminComponent implements OnInit, HttpInterceptor {
  xsrf: string   = <string>this.cookieExtractor.getToken()

  form: FormGroup = new FormGroup({
      username: new FormControl('', Validators.required),
      password: new FormControl('', Validators.required)
    }
  );
  submitted = false
  1. Add in previous component this important function
 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  request = request.clone({
    headers:  new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded', 'Cookie': this.xsrf }),
    withCredentials: true
  });

  return next.handle(request);
}

So the main problem which I have faced with writing application on both frontend and backend service that content-type must be application/x-www-form-urlencoded and not application/json (you can check via Postman sending request in Django-admin area). Hope that this solution will help you!

πŸ‘€Hayk Eminyan

Leave a comment