Skip to content

Instantly share code, notes, and snippets.

@blacktambourine
Last active October 14, 2015 11:56
Show Gist options
  • Save blacktambourine/45e7d2ffc852d917c040 to your computer and use it in GitHub Desktop.
Save blacktambourine/45e7d2ffc852d917c040 to your computer and use it in GitHub Desktop.
Angular JS Anti-forgery implementation
var corpServices = angular.module('corpApp.corpServices', ['ngResource']);
(function ()
{
//#region Common Service Methods
var serviceRootPath = '/api/';
//add anti-forgery token to all Authenticated GET and POST requests
var AntiForgeryRequest = function (enableCache)
{
var details =
{
'get': { method: 'GET', headers: { 'X-XSRF-Token': angular.element('input[name="__RequestVerificationToken"]').attr('value') }, cache: enableCache },
'post': { method: 'POST', headers: { 'X-XSRF-Token': angular.element('input[name="__RequestVerificationToken"]').attr('value') } }
};
return details;
}
//regular request for unauthenticated users
var AnonymousRequest = function (enableCache) {
var details =
{
'get': { method: 'GET', cache: enableCache },
'post': { method: 'POST' }
};
return details;
}
var newService = function (serviceRoute, parameterObj, enableCache, authenticatedOnly)
{
var service =
[
'$resource', function ($resource)
{
if (authenticatedOnly)
{
return $resource(serviceRoute, parameterObj, AntiForgeryRequest(enableCache));
}
else
{
return $resource(serviceRoute, parameterObj, AnonymousRequest(enableCache));
}
}
];
return service;
}
//#endregion
//#region Service Definitions
corpServices.factory('CalendarListService', newService(serviceRootPath + 'CalendarList/:id', { id: '@id' }, false, true));
//#endregion
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment