4

I recently updated a site I'm working on to check for anti-forgery tokens on all POST requests. For ajax requests I have put a prefilter on to check for the anti forgery token and add it to the headers

$.ajaxPrefilter(function (options, localOptions, jqXHR) {
    if (options.type == "POST") {
        var token = GetAntiForgeryToken();
        jqXHR.setRequestHeader(token.name, token.value);
    }
});

The site also has admin tools when logged in as an admin that uses CORS to send data to the separate admin site. One of these tools is an AJAX post request. The header is added to the request and it works correctly.

The other tool is a GET request which returns a form, which is displayed in a dialog. This works fine. However when the form is submitted, the preflight OPTIONS request is met with a 302, and I get the error "Response for preflight is invalid (redirect)"

If I remove the ajaxPrefilter, the form post works, but the straight post request does not. With the Prefilter on, the straight post request works, but the form post does not. I'm pretty lost. The antiforgery header is allowed in Access-Control-Allow-Headers. The requests for both are:

OPTIONS http://localhost:64789/Example/Example/?_=1464356730712 HTTP/1.1
Host: localhost:64789
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:64947
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
Access-Control-Request-Headers: __requestverificationtoken, accept, content-type
Accept: */*
Referer: http://localhost:64947/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

This one returns 302.

OPTIONS http://localhost:64789/Example2/Example2/ HTTP/1.1
Host: localhost:64789
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:64947
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
Access-Control-Request-Headers: __requestverificationtoken, accept, content-type
Accept: */*
Referer: http://localhost:64947/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6

This one returns 200.

Any help would be really useful.

Bonnotbh
  • 475
  • 5
  • 23
  • Your question is not straight forward. please provide only general and useful parts... – ReZa Jun 03 '16 at 20:50

2 Answers2

1

This was fixed by adding [HttpGet] attribute to the get method for the form.

Bonnotbh
  • 475
  • 5
  • 23
0

I think that you forgot to send content-type header for your form post. Try adding some of content-types from this answer: https://stackoverflow.com/a/35452170/1727132

Community
  • 1
  • 1
Jehy
  • 4,273
  • 1
  • 33
  • 54