简体   繁体   中英

Ajax anti-forgery POST with CORS preflight OPTIONS request (302 redirect)

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.

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

通过将[HttpGet]属性添加到表单的get方法来解决此问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM