I am using a third party library which spawns a raw XMLHttpRequest
with new XMLHttpRequest
.
This bypasses my CSRF protection and gets shot down by my rails server.
Is there a way to globally add a predefined CSRF token ($('meta[name=csrf-token]').attr('content')
) to ALL instances of XMLHttpRequest
at instantiation time?
If you need a Jquery independent solution you could use:
you can wrap the ajax open() method to open and then set the header right away:
I'd recommend to intercept calls to the
send
method:This won't add the header at instantiation time, but right before the request is sent. You can intercept calls to
new XMLHttpRequest()
as well, but that won't be helpful as you need to wait with adding the header untilopen
was called.You might also want to include a test for the target URL of the request, so that you only add the header when your own api is called. Not doing so might leak the token elsewhere, or might even break cross-domain CORS calls that don't allow this header.