Last active
July 3, 2017 15:50
-
-
Save angelix/11355094 to your computer and use it in GitHub Desktop.
AngularJS CSRF Request Interceptor (for SailsJS)
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
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'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Great thanks!