Search code examples
corsbreeze

breezejs : configuring service for CORS


I can access my web api service using a standard jquery ajax call:

$.ajax('http://service/method', {
contentType: 'application/json',
type: 'GET',
xhrFields: {
    withCredentials: true
  }
})

On the server side the webconfig file is configured as such:

 <customHeaders>
    <clear/>
    <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
    <add name="Access-Control-Allow-Origin" value="http://localhost:1502" />
    <add name="Access-Control-Allow-Headers" value="Content-Type,X-Requested-With, Authorization" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>

For now, I'm trying to reach the service from a local website running on port 1502.

However, when using breeze, I don't see how I can specify the withCredential parameter, and as a result I get a 401 error.


Solution

  • Look at the Breeze "ajax adapter". The following approach would add "withCredentials" to every Breeze XHR request.

    // get the current default Breeze AJAX adapter
    var ajaxAdapter = breeze.config.getAdapterInstance("ajax");
    // merge 'withCredentials' into the settings Breeze passes to the jQuery.ajax method
    ajaxAdapter.defaultSettings = {
          xhrFields: {
              withCredentials: true
          }
    };
    

    You could make a more clever adapter if you need to add this (or other information) to the request conditionally (e.g., for certain URLs and not others).