From e49de02d9509fd020cb1319851aae4b13bb86b4c Mon Sep 17 00:00:00 2001 From: bmacharia Date: Sat, 5 Jan 2019 19:32:55 +0300 Subject: [PATCH] Add ASP.NET ValidateAntiForgeryToken fix Jtable ajax calls to controler actions marked with [ValidateAntiForgeryToken] may not work because Antiforgery checks the request header for an antiforgery token which is then compared with the cookies token. If they don't match or the token is missing, the server responds with error 400. All this is to prevent Cross-Site Request Forgery (CSRF) Attacks. This fix attempts to manage this by adding a security option where a antiforgerytoken can be passed, this is then added to the ajax call header for server side validation. usage would be like: var token = 'gettokenvalue' $('#CategoriesContainer').jtable( { title: 'Categories', paging: false, sorting: false, security: { antiforgerytoken: token }, actions: {---------- --- dev/jquery.jtable.core.js | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/dev/jquery.jtable.core.js b/dev/jquery.jtable.core.js index 105f4198..33a854bf 100644 --- a/dev/jquery.jtable.core.js +++ b/dev/jquery.jtable.core.js @@ -22,6 +22,7 @@ //Options actions: {}, fields: {}, + security: { antiforgerytoken: null}, animationsEnabled: true, defaultDateFormat: 'yy-mm-dd', dialogShowEffect: 'fade', @@ -107,7 +108,8 @@ this._normalizeFieldsOptions(); this._initializeFields(); this._createFieldAndColumnList(); - + this._addAntiforgeryToken(); + //Creating DOM elements this._createMainContainer(); this._createTableTitle(); @@ -117,9 +119,17 @@ this._createErrorDialogDiv(); this._addNoDataRow(); - this._cookieKeyPrefix = this._generateCookieKeyPrefix(); + this._cookieKeyPrefix = this._generateCookieKeyPrefix(); + }, + /* Adds antiforgery token for MVC razor pages. to prevent cross-site request forgery by adding token to ajax call header + *************************************************************************/ + _addAntiforgeryToken: function () { + var self = this; + if (self.options.security.antiforgerytoken !== null ) { + var headerobj = JSON.parse('{ "RequestVerificationToken":"' + self.options.security.antiforgerytoken + '" }'); + self.options.ajaxSettings.headers = headerobj; + } }, - /* Normalizes some options for all fields (sets default values). *************************************************************************/ _normalizeFieldsOptions: function () {