Skip to content

Instantly share code, notes, and snippets.

@sdeering
Created August 11, 2014 15:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdeering/4356baed3692d26ab778 to your computer and use it in GitHub Desktop.
Save sdeering/4356baed3692d26ab778 to your computer and use it in GitHub Desktop.
injectorsauce with meta tag check
/**
* CSRF Token Security.
*/
(function() {
angular.module("app").config(['$httpProvider', function ($httpProvider) {
//check for token in meta tag
var csrf_token = $('meta[name=csrf-token]').attr('content');
if (csrf_token) {
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = csrf_token;
console.log('csrf_token = '+csrf_token+' (set by meta tag).');
} else {
//if token is not found, try requesting it.
var $injector = angular.injector(['ng']);
$injector.invoke(function($http, $rootScope) {
$rootScope.$apply(function() {
$http.get("/api/auth/csrf_token").then(function(response) {
$httpProvider.defaults.headers.common['X-CSRF-TOKEN'] = response.data.csrf_token;
console.log('csrf_token = '+response.data.csrf_token+' (set by http request).');
});
});
});
}
}]);
})();
@sdeering
Copy link
Author

@davemo
Copy link

davemo commented Aug 11, 2014

Ah nice, this makes sense :)

@davemo
Copy link

davemo commented Aug 11, 2014

And you are still using automatic bootstrap, as I don't see a call to angular.bootstrap here, right?

@sdeering
Copy link
Author

Yeah that's right, adding it to the config of the main app module seems to work nicely. Also, if it's a SPA I think it might be a good idea to collect a fresh CSRF Token (by HTTP) when the user logs out so that they are able to log in again without needing to refresh the page.

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