Created
August 11, 2014 15:14
-
-
Save sdeering/4356baed3692d26ab778 to your computer and use it in GitHub Desktop.
injectorsauce with meta tag check
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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).'); | |
}); | |
}); | |
}); | |
} | |
}]); | |
})(); |
Ah nice, this makes sense :)
And you are still using automatic bootstrap, as I don't see a call to angular.bootstrap
here, right?
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
Based on @davemo's injectorsauce. https://gist.github.com/davemo/6141699