Search code examples
odatabreezeasp.net-web-api2single-page-applicationazure-active-directory

Passing Authentication from WebApp to WebAPI using BreezeJS


I am having two web applications, one a SPA using AngularJS + BreezeJS and the other a WebAPI. We are building authorization in the WebAPI and the results get filtered based on user access. We want the user to sign-in into organization Azure AD in the SPA and pass the same authentication to WebAPI.

I am using ADAL JS library for authentication in SPA and have successfully handled that. However, I am not able to pass the same authentication to WebAPI using BreezeJS. Our WebAPI is OData v3 and without authn, Breeze works fine. We have customized the defaultHttpClient to add customer headers for DataVersion and MaxDataVersion since DataJS needs it.

var oldClient = OData.defaultHttpClient;

var myClient = {
  request: function (request, success, error) {
    request.headers.DataServiceVersion = '3.0';
    request.headers.MaxDataServiceVersion = '4.0';

    return oldClient.request(request, success, error);
  }
};

OData.defaultHttpClient = myClient;

However, I am not sure how to pass authentication token.

I have done following in entityManager

var ajaxAdapter = breeze.config.getAdapterInstance("ajax");
ajaxAdapter.defaultSettings = {
  xhrFields: {
    withCredentials: true
  }
};

as per the comments by Ward Bell on one of the posts by John Papa. However, this does not seem to be working. Need help.

Thanks Hemant


Solution

  • After some tinkering with the HTTP requests, I found out that the Bearer token that we were expecting to be passed on to server was actually not happening. Reason being we were not using ajaxAdapter in breeze. We had to add that header ourselves and send the request. We had setup an application in Azure AD. We had to pickup the key for the client application to get the token from storage. This prefixed with "Bearer " did the trick. Here is the sample code for custom adapter:

            var oldClient = OData.defaultHttpClient;
    
            var myClient = {
                request: function (request, success, error) {
                    request.headers.DataServiceVersion = '3.0';
                    request.headers.MaxDataServiceVersion = '3.0';
                    request.headers.Authorization = "Bearer " + adalAuthenticationService.getCachedToken('<<your AD client app key here>>');
                    return oldClient.request(request, success, error);
                }
            };
            OData.defaultHttpClient = myClient;