Ajax Request header field Key is not allowed by Access-Control-Allow-Headers

NorianNyx picture NorianNyx · Oct 7, 2014 · Viewed 54.6k times · Source

Trying to build a DNN Service Framework WebAPI but I'm having trouble consuming it with CORS. I have all of the appropriate headers (I think) but it still doesn't seem to be working.

Error:

XMLHttpRequest cannot load http://www.dnndev.me/mysite/builder/API/echo?message=Hello+World&_=1412707749275. Request header field Key is not allowed by Access-Control-Allow-Headers.

Request Headers:

Remote Address: 127.0.0.1:80
URL: http://www.dnndev.me/mysite/builder/API/echo?message=Hello
Request Method: OPTIONS
Status Code: 200 OK
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Access-Control-Request-Headers: accept, key
Access-Control-Request-Method: GET
Connection: keep-alive
Host: www.dnndev.me
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.124 Safari/537.36

Response Headers:

Access-Control-All-Headers: Origin, X-Requested-With, Content-Type, Accept, Key
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Length: 13
Content-Type: application/json; charset=utf-8
Date: Tue, 07 Oct 2014 18:49:10 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/7.5

Generally, this error would be caused by not having the appropriate header in 'Access-Control-All-Headers'. However, I am sending the correct response to allow ajax to continue with its request. It simply refuses to.

Here is my ajax call to the method:

$.ajax({
    type: 'GET',
    url: 'http://www.dnndev.me/mysite/builder/API/echo',
    dataType: 'json',
    data: { message: 'Hello' },
    crossDomain: true,
    headers: { 'Key': 'Bearer 7680ff6e-1362-4236-a9cd-c6bc8b6f13ea' },
    success: function (result) { console.log(result); }
});

Probably obvious, but this only happens on cross domain requests and only when I include the custom header (therefore procing ajax to do an OPTIONS).

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 7, 2014

Your server responds with the following custom header to the preflight request:

Access-Control-All-Headers: Origin, X-Requested-With, Content-Type, Accept, Key

whereas if you (or the person who wrote this server) read carefully about CORS he should have responded with:

Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Key

Now the client client could go ahead and use the Key custom header.

This being said, Bearer is quite specific to OAuth 2 which is sent throughout the Authorization header. Using Key seems like a terrible violation of RFCs and stuff and a wheel reinvention kinda.