Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@sdeering sdeering commented Aug 11, 2014

@davemo

This comment has been minimized.

Copy link

@davemo davemo commented Aug 11, 2014

Ah nice, this makes sense :)

@davemo

This comment has been minimized.

Copy link

@davemo 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

This comment has been minimized.

Copy link
Owner Author

@sdeering sdeering commented Aug 21, 2014

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
You can’t perform that action at this time.