CORS Support within WCF REST Services

Kevin picture Kevin · Aug 29, 2011 · Viewed 21.4k times · Source

I have a WCF REST service hosted within a Windows service and I would like to send the Access-Control-Allow-Origin HTTP header (defined as part of CORS) with every response.

My attempted solution was to have something like the following within an IDispatchMessageInspector implementation:

public void BeforeSendReply(ref Message reply, object correlationState)
{
    var httpResponse = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
    if (httpResponse != null)
    {
        // test of CORS
        httpResponse.Headers["Access-Control-Allow-Origin"] = "*";
    }
}

Normally this would work, but unfortunately my service also uses HTTP basic authorization, which means that when a request comes in without the Authorization header, WCF automatically sends a 401 response asking for credentials. Unfortunately WCF does not call my IDispatchMessageInspector during this initial exchange, so Access-Control-Allow-Origin header is not added to the initial exchange.

The problem occurs when I try to call the service from a browser. CORS specifies that cross-origin requests should only be allowed if the origin domain matches the domain listed in the Access-Control-Allow-Origin response header (* matches all domains). Unfortunately when the browser sees the initial 401 response without the Access-Control-Allow-Origin header, it prevents access (according to the same origin policy).

Is there any way add a header to the initial 401 response sent automatically by WCF?

Answer

granadaCoder picture granadaCoder · Oct 14, 2011

This guy saved my day.

http://blogs.microsoft.co.il/blogs/idof/archive/2011/07.aspx

I am going to place some of his notes here, just in case that web page dies some day. (I hate finding "Your answer is right HERE" links, and then the link is dead.)

<behaviors> 
  <endpointBehaviors> 
    <behavior name="webSupport"> 
      <webHttp /> 
      <CorsSupport /> 
    </behavior> 
  </endpointBehaviors> 
</behaviors> 
<extensions> 
  <behaviorExtensions> 
    <add name="CorsSupport" type="WebHttpCors.CorsSupportBehaviorElement, WebHttpCors, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" /> 
  </behaviorExtensions> 
</extensions> 
<services> 
  <service name="Service.JSonService"> 
    <endpoint address="http://localhost:8080" behaviorConfiguration="webSupport” binding="webHttpBinding" contract="Service.IJSonService" /> 
  </service> 
</services>

Now, you have to find his downloadable library called "WebHttpCors.dll".

But there is enough there (above) to help you google/bing your way to a resolution.

The part that was throwing me for a loop (in my scenario) is that IE was working, but Firefox was not working.

My originating page was:

http://localhost:53692/test/WCFCallTestViaJQ14.htm

So my service is at:

http://localhost:8002/MyWCFService/MyWCFMethodByWebGet?state=NC&city=Raleigh

So I had localhost <<-->> localhost traffic.

**** But the ports were different. (53692 and 8002) ****

IE was ok with it. Firefox was not ok with it.

Then you gotta remember that each browser handles their .Send() requests differently (inside JQUERY that is).

It all makes sense now.

//JavaScript snipplet from JQuery library

if (window.XMLHttpRequest) {

    returnObject = new XMLHttpRequest();

} else if (window.ActiveXObject) {

    returnObject = new ActiveXObject("Microsoft.XMLHTTP");

} else {

msg = "Your browser doesn't support AJAX!";

}

Here are some key words, phrases that I've been googling/binging that finally led me somewhere.

    Result: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.statusText]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: http://localhost:53692/test/WCFCallTestViaJQ14.htm :: HandleJQueryError :: line 326" data: no]


XMLHttpRequest Send "NS_ERROR_FAILURE"

JQuery Ajax WCF Self Hosted CORS JSON

NOW, YOU NEED TO READ HIS BLOG BLOGS TO UNDERSTAND WHAT THE CODE IS DOING:

For example, he says:

“Access-Control-Allow-Origin” header with the value of “*”

This may or may not be what you want. You may want to have better control of this value (headers) and the others (methods and the origins).

Development environment is one thing. (Use all the *'s you want).

Production is something else, you may want to tweak down those * values to something more discriminate. In a nutshell, you need to understand what CORS is actually doing for you in terms of security, and not just add a behavior that lets everything in.

  allowed-origins: '*'
  allowed-headers: '*'
  allowed-methods: '*'