Integrating AngularJS with Azure Active Directory Services and Office 365/SharePoint, Part 5

Communicating with Office 365/SharePoint APIs through an HttpHandler

Dan Wahlin

by Dan Wahlin on 2/8/2015

Share this:

Article Details

Date Revised:

Applies to:
Ajax, AngularJS, Dan Wahlin, Development, Office 365, SharePoint Online

Part 4 of this series discussed the Azure Active Directory (AAD) and OWIN code required by the Expense Manager application in order to enable users to authenticate into AAD. It also discussed the flow of ID and access tokens and how they’re used to gain access to Office 365/SharePoint resources. Now that the authentication piece is in place we can move on to the next part of the application.

In this article I’ll discuss the process of communicating with Office 365 SharePoint APIs. Although direct communication from AngularJS to Office 365 isn’t currently supported, it’s still possible to make an Ajax-style call from AngularJS and call into the cloud-hosted APIs. This article will discuss that process and show the code that’s required to make it happen.

You can find the code that’s discussed throughout this series on the OfficeDev Github site. The included readme walks through the process of setting up the necessary SharePoint lists that will be queried in the Expense Manager application. If you’re new to Office 365 and the overall environment you can go here to learn more about creating a tenant and configuring a SharePoint instance.

Let’s start the discussion by talking about the challenges that arise as a browser makes cross-domain calls.

Cross-domain Ajax calls

If you’ve worked much with JavaScript and Ajax calls in the browser then you’re probably aware that cross-domain requests don’t work too well. In fact, they don’t work at all without extra effort. This is due to the security restrictions built into browsers that try to protect us from sites that might attempt to take information we’ve entered and send it off to another domain. If (the local site) tries to make an Ajax/XmlHttpRequest (XHR) to (the remote site) the browser will shut it down and throw an exception as shown in Figure 1.

Cross-domain Ajax calls are not allowed in browsers by default

Figure 1. Cross-domain Ajax calls aren’t allowed in browsers by default.

While there are several workarounds to this challenge such as JSONP and Cross-Origin Resource Sharing (CORS), the Office 365 and SharePoint APIs don’t currently support them. That limitation will change in the near future, but for the time being you’ll have to resort to other techniques to communicate with Office 365 APIs using Ajax.

The Expense Manager application makes several Ajax/XHR calls using AngularJS factories to retrieve and modify data stored in three SharePoint lists:  Employees, Expenses and States. To successfully make these calls into Office 365, the application relies on a middleman service or what I refer to as a web proxy. The web proxy is server-side HttpHandler class written in C# that lives in the same domain as the Expense Manager application. For example, may be the local site that serves up the Expense Manager application. The web proxy lives on the server and the client calls into it any time it needs to make a remote XHR call to Office 365. Once the call is received, the web proxy calls into the remote site, receives data back from the site, and forwards it to the AngularJS factory. Figure 2 shows the overall flow.

A web proxy middleman service to allow Ajax calls to be made to Office 365 APIs

Figure 2. Using a web proxy middleman service to allow Ajax calls to be made to Office 365 APIs.

Let’s take a look at the web proxy and how it works.

Introducing the WebProxy HttpHandler

In situations where XHR calls need to be made into Office 365 or any remote service and you don’t have the option of using JSONP, CORS (something that Office 365 will support in the near future), or another technique, server-side code can be added into the local domain to handle the XHR calls. The Expense Manager application relies on an HttpHandler named WebProxy.ashx to act as the middleman between the local site and the remote Office 365 APIs.

Why was an HttpHandler chosen as opposed to a Web API controller, an MVC controller or another server-side technology? Although there isn’t a single option that’s “the best” for this scenario, HttpHandlers are fairly straightforward to write and don’t require a lot of supporting infrastructure to make them work. The others options mentioned could certainly get the job done as well so I’d recommend picking whatever is best for your application needs. For this application an HttpHandler was chosen.

The shell for the WebProxy.ashx.cs class is shown in Listing 1.

using ExpenseManager.SharePointHelpers;
using ExpenseManager.Utils;
using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.SessionState;

namespace ExpenseManager.Handlers
    public class WebProxy : HttpTaskAsyncHandler, IRequiresSessionState
        public override async Task ProcessRequestAsync(HttpContext context)

        private HttpWebRequest CreateRequest(
         HttpContext context, string token)

        private void CreateResponse(
         HttpContext context, HttpWebRequest request)

        public bool IsReusable
            get { return false; }
Listing 1. The WebProxy.ashx.cs shell code.

The first part of the code that may stand out is that WebProxy doesn’t derive from the standard HttpHandler class. Because it requires async functionality (see the ProcessRequestAsync() method for example) it derives from HttpTaskAsyncHandler, which is a newer class available in the framework. By deriving from it you can leverage the async and await keywords built-into C# to simplify the process of making async calls.

In addition to deriving from HttpTaskAsyncHandler, WebProxy also implements the IRequiresSessionState interface. This is a marker interface (it doesn’t have any members in it) that allows session functionality to be used if needed in the handler. The original version of the application relied on accessing Office 365 session information from within WebProxy and although that code has been removed, the interface was left in case sessions were ever needed. However, it could technically be removed if you know you don’t need any session functionality in your application.

The ProcessRequestAsync() method

The ultimate goal of creating the WebProxy HttpHandler is to allow AngularJS factories to make XHR calls to it which are then forwarded to Office 365 APIs. As an XHR call is made into WebProxy the ProcessRequestAsync() method will be called. It handles getting an access token that can be used to call into Office 365 and then initiates an HTTP request to the remote service. Listing 2 shows the complete code for the ProcessRequestAsync() method.

public override async Task ProcessRequestAsync(HttpContext context)
        //Get SharePoint Access Token
        var token = await SharePointAuth.GetAccessToken(

        if (!String.IsNullOrEmpty(token))
            Debug.WriteLine("Bearer token found: " + token);
            HttpWebRequest request = CreateRequest(context, token);
            CreateResponse(context, request);
            Debug.WriteLine("No bearer token found in WebProxy.ashx.cs");
            //context.Response.StatusCode = (int)HttpStatusCode.Redirect;

    catch (Exception exp)
        Debug.WriteLine("Error in WebProxy ProcessRequest: " + 

Listing 2. The ProcessRequestAsync() method handles getting an Office 365 API access token an initiating a web request.

The first line of code in the ProcessRequestAsync() method makes a call to a custom class named SharePointAuth. This class wraps Office 365 access token functionality and makes it easy to integrate with the AAD and OWIN code covered in the Part 4 of this series. The GetAccessToken() method that’s called is shown in Listing 3.

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Office365.Discovery;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using ExpenseManager.Utils;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;

namespace ExpenseManager.SharePointHelpers
    public static class SharePointAuth
        public static AuthenticationContext GetAuthContext()
            var signInUserId = ClaimsPrincipal.Current.FindFirst(
            var tokenCache = new EFADALTokenCache(signInUserId);
            var authContext = new AuthenticationContext(
              SettingsHelper.AzureADAuthority, tokenCache);
            return authContext;
        public static async Task<string> GetAccessToken(string resource)
            var userObjectId = ClaimsPrincipal.Current.FindFirst(
            var clientCredential = new ClientCredential(
              SettingsHelper.ClientId, SettingsHelper.ClientSecret);
            var userIdentifier = new UserIdentifier(userObjectId, 
            var authContext = GetAuthContext();
            var authResult = await authContext.AcquireTokenSilentAsync(
               resource, clientCredential, userIdentifier);
            return authResult.AccessToken;

Listing 3. Getting an Office 365 access token using the SharePointAuth class.

The GetAccessToken() method in SharePointAuth gets the signed in user’s ID, pulls from the Entity Framework token cache by calling GetAuthContext() (the token cache was covered in the previous article), and then uses the user information to obtain an access token by making an async call to AcquireTokenSilentAsync(). The resulting token can be used to access Office 365 APIs that the user is authorized to call.

As a quick refresher, the process of working with ID and access tokens is shown in Figure 3. You may recall seeing this in the previous article but it’s important to understand the flow of tokens so it’s repeated again in this article.

The flow as a user logs into AAD, gets an ID token, and then accesses an application and additional resources with an access token

Figure 3. The flow as a user logs into AAD, gets an ID token, and then accesses an application and additional resources with an access token. This image is from

Once the access token is returned from the SharePointAuth class, WebProxy creates an HttpWebRequest object and adds the token to the request headers. Let’s take a closer look at that process.

Creating an HttpWebRequest Object and Using the Access Token

WebProxy relies on the HttpWebRequest and HttpWebResponse classes in .NET to forward any XHR calls that it receives to Office 365. To handle this an HttpWebRequest object is first created and the access token mentioned earlier is added into it’s headers collection. Listing 4 shows the CreateRequest() method that is called from ProcessRequestAsync() in WebProxy.

private HttpWebRequest CreateRequest(HttpContext context, string token)
    var url = context.Server.UrlDecode(context.Request["url"]);
    var contextInfoRequest = context.Request.Headers["ContextInfoRequest"];
    var requestDigest = context.Request.Headers["X-RequestDigest"];
    var ifMatch = context.Request.Headers["If-Match"];
    var restMethod = context.Request.HttpMethod.ToUpper();
    var accept = context.Request.Headers["Accept"];
    var xHttpMethod = context.Request.Headers["X-HTTP-Method"];
    var contentTypeVerbs = new string[] { "PUT", "POST", "MERGE" };


    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Accept = "application/json;odata=verbose";
    request.ContentType = "application/json;odata=verbose";
    request.Method = restMethod;
    request.Headers.Add("Authorization", "Bearer " + token);

    if (contextInfoRequest == "true") request.ContentLength = 0;
    if (requestDigest != null) request.Headers.Add("X-RequestDigest",
    if (ifMatch != null) request.Headers.Add("If-Match", ifMatch);
    if (xHttpMethod != null) request.Headers.Add("X-HTTP-Method",
    if (Array.IndexOf(contentTypeVerbs, restMethod) >= 0)
        var bodyStream = context.Request.GetBufferedInputStream();
        var dataStream = request.GetRequestStream();
    return request;

Listing 4. Making an HttpWebRequest object and modifying HTTP headers.

The first line of code in CreateRequest() extracts the URL that the client-side code is attempting to call and stores it in a variable named URL. To keep the client-side code simple (client-side code will be covered in detail in the next article), the AngularJS code simply passes the Office 365 URL that it would like to call up to the WebProxy using a query string parameter named “url”.

Here’s an example of a URL that would be passed to WebProxy. It calls into a SharePoint list named Employees and retrieves several columns.


Once the remote URL to call is obtained, the CreateRequest() method accesses several header values that the client may have set and forwarded to WebProxy such as ContextInfoRequest, X-RequestDigest, If-Match and others. From there, the code creates a new HttpWebRequest object, sets several properties on it such as Accept, ContentType and Method, and then adds the access token mentioned earlier into the Authorization header. This header value will be passed to Office 365 and used to either accept or reject the user request.

Finally, the CreateRequest() method accesses the stream of data that is sent to WebProxy from the client-side JavaScript code and moves it into the HttpWebRequest’s stream (see the final “if” statement in Listing 4). This code simply copies whatever the client sends to WebProxy into the new request that is being made to Office 365.

Accessing the HttpWebResponse data

Once the HttpWebRequest object is created the ProcessRequestAsync() method shown in Listing 2 calls another method in WebProxy named CreateResponse() (see Listing 5).

private void CreateResponse(HttpContext context, HttpWebRequest request)
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (var stream = response.GetResponseStream())
        var ms = new MemoryStream();
        ms.Seek(0, SeekOrigin.Begin);
        if (ms.Length > 0)
            context.Response.ContentType = "application/json";

Listing 5. Processing the response received from an Office 365/SharePoint API call.

This code starts by accessing the response stream. From there it copies the response data into a new MemoryStream object which is then written to the HttpContext’s output stream and sent back to the client. The MemoryStream intermediary is necessary here because requests that do not return any bytes in the stream can cause issues if they’re not processed correctly. By checking the length of the MemoryStream the code can ensure that responses that return data and those that don’t work correctly and don’t cause any client-side errors.

Although there’s a fair amount of code required to get WebProxy off the ground and working, it can be used to call virtually any Office 365 service API. Once CORS support is in place for Office 365 you can eliminate this type of middleman requirement.

So what does the client-side code look like? While that’ll be the subject of the next article, here’s a quick look into an AngularJS factory function that calls WebProxy to retrieve employee data from an Office 365 SharePoint list (see Listing 6).

factory.getEmployeesSummary = function (pageIndex, pageSize) {
    var url = serviceBase + encodeURIComponent(baseSPListsUrl +  
      "getByTitle('Employees')/items?$select=ID,FirstName,LastName,” +
    return getPagedResource(url, pageIndex, pageSize);

Listing 6. Using an AngularJS factory to call WebProxy which in turn forwards the call to Office 365/SharePoint.


In Part 5 of this article series you’ve learned about the WebProxy class and how it’s used as a middleman service between the Expense Manager application’s client-side code and Office 365/SharePoint APIs. You’ve also seen how an Office 365 access token can be obtained and used to call remote APIs.

In the next article in this series you’ll learn more about the client-side code and see how AngularJS can be used to interact with Office 365 APIs.

Topic: Development

Sign in with

Or register