@@ -290,8 +290,22 @@ function csrfprotector_init() {
290
290
function new_send ( data ) {
291
291
if ( this . method . toLowerCase ( ) === 'post' ) {
292
292
if ( data !== null && typeof data === 'object' ) {
293
- data . append ( CSRFP . CSRFP_TOKEN , CSRFP . _getAuthKey ( ) ) ;
293
+ data [ CSRFP . CSRFP_TOKEN ] = CSRFP . _getAuthKey ( ) ;
294
294
} else {
295
+ // Added support for content type == application / json
296
+ if ( this . headers && 'Content-Type' in this . headers
297
+ && this . headers [ 'Content-Type' ] === 'application/json' ) {
298
+ try {
299
+ data = JSON . parse ( data )
300
+ data [ CSRFP . CSRFP_TOKEN ] = CSRFP . _getAuthKey ( ) ;
301
+ return this . old_send ( JSON . stringify ( data ) ) ;
302
+
303
+ } catch ( ex ) {
304
+ console . log ( "[ERROR] [CSRF Protector] Unable to parse content " ,
305
+ "when content-type is application/json" , ex ) ;
306
+ }
307
+ }
308
+
295
309
if ( typeof data != "undefined" ) {
296
310
data += "&" ;
297
311
} else {
@@ -303,12 +317,27 @@ function csrfprotector_init() {
303
317
return this . old_send ( data ) ;
304
318
}
305
319
320
+ /**
321
+ * Wrapper method to override setRequestHeader method of
322
+ * XMLHttpRequests
323
+ * @param : header - header name
324
+ * @param : value - header value
325
+ */
326
+ function new_setRequestHeader ( header , value ) {
327
+ if ( ! this . headers ) this . headers = { } ;
328
+ this . headers [ header ] = value ;
329
+
330
+ this . old_setRequestHeader ( header , value ) ;
331
+ }
332
+
306
333
if ( window . XMLHttpRequest ) {
307
334
// Wrapping
308
335
XMLHttpRequest . prototype . old_send = XMLHttpRequest . prototype . send ;
309
336
XMLHttpRequest . prototype . old_open = XMLHttpRequest . prototype . open ;
337
+ XMLHttpRequest . prototype . old_setRequestHeader = XMLHttpRequest . prototype . setRequestHeader ;
310
338
XMLHttpRequest . prototype . open = new_open ;
311
339
XMLHttpRequest . prototype . send = new_send ;
340
+ XMLHttpRequest . prototype . setRequestHeader = new_setRequestHeader ;
312
341
}
313
342
if ( typeof ActiveXObject !== 'undefined' ) {
314
343
ActiveXObject . prototype . old_send = ActiveXObject . prototype . send ;
0 commit comments