Skip to content

Instantly share code, notes, and snippets.

@macedd
Created January 27, 2016 23:48
Show Gist options
  • Save macedd/000708f28d56bede464b to your computer and use it in GitHub Desktop.
Save macedd/000708f28d56bede464b to your computer and use it in GitHub Desktop.
(function(){
/**
* Module to workout CORS requests with CSRF
*/
angular.module('CorsCSRF')
.config(function($httpProvider)
{
// CSRF Interceptor
$httpProvider.interceptors.push(function($cookies) {
return {
request: function(config) {
var token = $cookies.get('CSRF-TOKEN');
if (token && !config.headers['X-CSRF-TOKEN']) {
config.headers['X-CSRF-TOKEN'] = token;
}
return config;
},
response: function(response) {
// console.log(response);
return response;
},
};
});
})
.run(function($cookies, apiUrl) {
/**
* Check if CSRF Session Cookie is set
* Otherwise request it from app (synchronous)
*/
if (! $cookies.get('CSRF-TOKEN') ) {
// set cookie before further requests
var request = new XMLHttpRequest();
request.open('GET', apiUrl + '/auth/csrf', false); // `false` makes the request synchronous
request.send(null);
$cookies.put('CSRF-TOKEN', request.response);
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment