Many servers use CSRF as a security feature and you can certainly keep this feature in a hybrid app if you wish. CSRF is a way to ensure the client making a request is the same one that the server expects to make the request. This keeps someone from sniffing your cookie session data and making requests pretending to be you (and changing your password, for example).
To make for CSRF, we can tell $http to set the correct header for CSRF (might depend on your server framework, this one is for Django) using the specific cookie name:
angular.module('myApp', ['ngCookies'])
.run(['$http', '$cookies', function($http, $cookies) {
$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;
}]);
While I’ve found this to work pretty well, if the CSRF token changes mid-session (for example if a new user signs up) the token won’t update. To fix this, we can use an HTTP Interceptor to always set the correct CSRF header value before each request:
angular.module('myApp')
.provider('myCSRF',[function(){
var headerName = 'X-CSRFToken';
var cookieName = 'csrftoken';
var allowedMethods = ['GET'];
this.setHeaderName = function(n) {
headerName = n;
}
this.setCookieName = function(n) {
cookieName = n;
}
this.setAllowedMethods = function(n) {
allowedMethods = n;
}
this.$get = ['$cookies', function($cookies){
return {
'request': function(config) {
if(allowedMethods.indexOf(config.method) === -1) {
// do something on success
config.headers[headerName] = $cookies[cookieName];
}
return config;
}
}
}];
}]).config(function($httpProvider) {
$httpProvider.interceptors.push('myCSRF');
});
This will set the CSRF request header to the current value of the CSRF cookie for any request type not in allowedMethods.