Skip to content

Instantly share code, notes, and snippets.

@guillaumepiot
Created October 23, 2012 15:28
Show Gist options
  • Select an option

  • Save guillaumepiot/3939452 to your computer and use it in GitHub Desktop.

Select an option

Save guillaumepiot/3939452 to your computer and use it in GitHub Desktop.
ANGULARJS - Django CSRF Token header setup
var myApp = angular.module('myApp').config(function($httpProvider) {
$httpProvider.defaults.headers.post['X-CSRFToken'] = $('input[name=csrfmiddlewaretoken]').val();
});
@skyl

skyl commented Apr 21, 2013

Copy link
Copy Markdown

awesome, thanks.

@mbarchein

Copy link
Copy Markdown

Great

@sansb

sansb commented Aug 16, 2013

Copy link
Copy Markdown

Thank ye

@TechNickAI

Copy link
Copy Markdown

Very good idea, saved me time. 1 answer @changetip

@c3chandu

c3chandu commented Mar 7, 2014

Copy link
Copy Markdown

Good one. place the "X-CSRFToken" in common headers for better usage.
$httpProvider.defaults.headers.common['X-CSRFToken'] = $('input[name=csrfmiddlewaretoken]').val();

@adrienlachaize

Copy link
Copy Markdown

Perfect, thanks.

@CalebMuhia

Copy link
Copy Markdown

you can also have this in a http interceptor, and get the csrftoken from the cookies, like so

config.headers['X-CSRFToken'] = $cookies.csrftoken

@jedrichards

Copy link
Copy Markdown

@CalebMuhia isn't the whole point of a CSRF token that it isn't stored in a cookie?

@ailling

ailling commented Oct 14, 2014

Copy link
Copy Markdown

@jedrichards No. In fact, django always stores the csrf token in a cookie: https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax

And the docs recommend getting the value from the cookie for all javascript code (as opposed to obtaining it from the DOM).

@karllindmark

Copy link
Copy Markdown

@ailling: Good point!

@pasupulaphani

Copy link
Copy Markdown

Just put together a small lib just to make easy to use. Similar concept. https://github.com/pasupulaphani/angular-csrf-cross-domain

@budescode

Copy link
Copy Markdown

Where do I place this code.?

@guillaumepiot

Copy link
Copy Markdown
Author

I can't remember sorry, haven't worked with Angular in years...

@guillaumepiot

Copy link
Copy Markdown
Author

Looks like it's when you initialize your app, which is the html element with tag ng-app="myApp"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment