Created
January 27, 2016 23:48
-
-
Save macedd/000708f28d56bede464b to your computer and use it in GitHub Desktop.
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
(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