Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I set headers in cross domain json requests?

I have done some research on the internet, but I didn't manage to get the complete picture about this subject. Can anyone help to solve this answer for now and forever?

This is what I found so far:

  • It is possible to do cross domain call with jsonp. Altering headers in jsonp call is never allowed
  • It is possible to do cross domain call with json if the server allows it.

This is what I am trying to do :

$.ajax({
    type: "GET",
    crossDomain: true,
    beforeSend: function (request) {
        request.setRequestHeader("Authorization", "Bearer " + ($("#accesstoken").val()));
    },
    contentType: "application/json; charset=utf-8",
    url: myJSonServer + encodeURI(operation),
    dataType: 'json',
    cache: false,
    success: callback,
    error: function (jqXhr, textStatus, errorThrown) { alert(textStatus + ": " + errorThrown); }
});

This is what is happening:

  • When the myJSonServer is on the same domain, there is no problem at all
  • When the myJSonServer is on another domain the request is sent, but without the Bearer header

This Bearer header is part of the oAuth2 standard.

I'm aware of the fact that maybe this is not the best solution, setting the accessToken in the Browser. And I know I could use a proxy for this situation.

I am just curious if it is or will be possible to set the headers on a cross-domain json request?
Thanks

-- Problem solved

I was using MVC4 and added crossDomainScriptAccessEnabled="true" in the web.config. I thought this would be enough, but the answer of apsillers solved my problem. I have now added this in my web.config :

 <system.webServer>
     <httpProtocol>
         <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Authorization" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
like image 374
fantastischIdee Avatar asked Jan 04 '13 08:01

fantastischIdee


2 Answers

With JSONP, setting custom headers is not possible.

With CORS, the server must send the Access-Control-Allow-Headers header to allow uncommon request headers from the client. From the HTML5 Rocks CORS page:

Access-Control-Allow-Headers ... - Comma-delimited list of the supported request headers.

Thus, your server must send a Access-Control-Allow-Headers: Authorization to let the browser know it is permissible to send Authorization to the server with the request. Without this sever header, the browser will only send a few common headers with the request and ignore the rest.

like image 75
apsillers Avatar answered Oct 09 '22 15:10

apsillers


Since "jsonp" works by creating an script tag and using the attribute src= to load resource from another domain. So I don't think there is a way to modify request headers.

like image 25
ijse Avatar answered Oct 09 '22 17:10

ijse