Skip to content

Instantly share code, notes, and snippets.

@angelix
Last active July 3, 2017 15:50
Show Gist options
  • Save angelix/11355094 to your computer and use it in GitHub Desktop.
Save angelix/11355094 to your computer and use it in GitHub Desktop.
AngularJS CSRF Request Interceptor (for SailsJS)
app.factory('csrfRequestInterceptor' , function($q , $injector){
var _token = false;
return {
request : function(config){
var CSRF_URL = '/csrfToken';
if(config.url == CSRF_URL || config.method == "GET"){
return config;
}
// sailsjs hasn't time limit for csrf token, so it is safe to cache this
// remove this to request a new token
if(_token){
config.data._csrf = _token;
return config;
}
var deferred = $q.defer();
var $http = $injector.get('$http');
$http.get(CSRF_URL).success(function(response , status , headers){
if(response._csrf){
_token = response._csrf;
config.data._csrf = _token;
//config.headers['X-CSRF-Token'] = response._csrf;
}
deferred.resolve(config);
}).error(function(response , status , headers){
deferred.reject(response);
});
return deferred.promise;
}
}
});
app.config(function ($httpProvider) {
$httpProvider.interceptors.push('csrfRequestInterceptor');
});
@juanpasolano
Copy link

Great thanks!

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