Calling the Office 365 APIs with jQuery and Adal.js

Scot Hillier

by Scot Hillier on 11/3/2015

Share this:

Article Details

Date Revised:

Applies to:
ADAL.JS, Azure Active Directory (AAD), Azure Active Directory Authentication libraries, jQuery, Oath, Office 365 API, RESTful services, SharePoint, Unified API

Over the last 18 months, I have spent a significant amount of time building single-page applications (SPA) that interact with back-end RESTful services like SharePoint, Office 365, and others. When building these applications, I have typically used the Angular framework along with OAuth tokens for security. For simplicity when managing security tokens, I utilize the Active Directory Authentication Library for JavaScript (adal.js). If you follow my work on IT Unity, then you’ll know that I have already posted an article explaining the basics of this architecture and how the pieces fit together.

Along with building SPAs for customers, I have also spent a lot of time at conferences teaching others to do the same. Recently, I put on an all-day workshop in Amsterdam at the Unity Connect event on this very topic. What I find interesting about the audience for these events is that many of the developers are still using jQuery and have little experience with Angular. So, in this article, I am going to show the basics of creating jQuery-based applications that can call any of the available RESTful services exposed by Microsoft including SharePoint, OneDrive, Exchange, and the Unified API. The source code is available in the IT Unity GitHub repo.

It’s all about the plumbing

The more you work with modern development techniques in the cloud, the more obvious it becomes that the security plumbing is the hard part. For developers, this means mastering various OAuth flows to authenticate users and authorize applications. When learning OAuth, it’s important to understand that it exists to solve one and only one problem; specifically, it allows an application to perform a function on behalf of the current user without the user having to give up a password. That’s it.

Essentially, OAuth allows for the establishment of trust between two entities (the user and the app) that don’t trust each other. In order to do that, OAuth engages a third party that is trusted by both the user and the app. In the Microsoft world, that third party is Azure Active Directory (AAD).

In order to appreciate what OAuth does, you can compare it to the process of making a consumer purchase using a credit card. Think about purchasing a cup of coffee from Starbucks. In this scenario, you don’t want to give Starbucks direct access to your bank account; you simply don’t trust them with that kind of authority. So, you engage a third party that both you and Starbucks trust to facilitate the transaction through the use of a credit card. The credit card essentially gives Starbucks access to just the funds necessary to complete the transaction. The same idea applies when an app wants to tweet, update your status, access a document, or read your e-mail; you only want to give the app limited access, which is facilitated by a trusted third party.

In a financial transaction, the moment of using the credit card is relatively simple; you just put the card in a machine and enter your PIN. However, many things had to happen to prepare for the transaction. You had to register with a bank and get a credit card. The vendor had to set up an account to receive payment. All of these things involved identity verification, credit checks, etc. The same types of things happen in the OAuth realm; applications and users must register with AAD, identities must be verified, and permissions granted.

Fortunately for developers, Microsoft provides several Azure Active Directory Authentication libraries that embody the OAuth process and provide object abstractions that make it easier to program. This brings me back around to the topic at hand, which is using the Active Directory Authentication Library for JavaScript along with jQuery to access Office 365 APIs.

Setting the Client ID and permissions

In the OAuth world, applications you write are considered first-class principals. This means that applications are on par with end users as far as AAD is concerned. Applications that participate in OAuth flow are registered with AAD and get a username, password, and permissions exactly like an end user. Except for applications, we call the username the Client ID and the password the Client Secret. The Client ID is typically a GUID and the Client Secret is a base-64-encode string.

If you have an Office 365 tenancy, then you can access the associated AAD instance directly through the Azure portal. The detailed steps for registering an application are not specific to this article, but you can review them here. The important thing for using the Active Directory Authentication Library for JavaScript is to copy the Client ID from the registration and ensure the application permissions are properly set.

Once you have registered an application, you can copy the Client ID directly from the Azure portal on the configuration page for the application. The Active Directory Authentication Library for JavaScript will use this information to request an access token for the application. Figure 1 shows the Client ID in the portal.

Copy the Client ID directly from the Azure portal on the configuration page for the application

Figure 1, Copying the Client ID

Setting permissions for the registered application is done on the same page where the Client ID is located. Here, you can select services and permissions. In this sample, I’ve elected to give the application full control over the site collections in SharePoint online. Figure 2 shows the permissions in the portal.

Setting permissions for the registered application

Figure 2, Assigning application permissions

Coding the sample

In order to focus on the basic security flow, I have intentionally kept the sample code simple. The only elements on the page are links for logging in/out and some areas for displaying text. I have referenced only jQuery, adal.js, and a custom JavaScript library. Listing 1 shows the HTML for the sample page.

Listing 1, HTML page for the sample

    <a href="javascript:;" id="signInLink">Sign In</a>
    <a href="javascript:;" id="signOutLink">Sign Out</a>
    <p id="loginMessage"></p>
<script src="Scripts/jquery-1.11.3.js"></script>
<script src="Scripts/adal.js"></script>
<script src="app/scripts/app.js"></script>

The real focus of the sample is the custom JavaScript library that makes use of the Active Directory Authentication Library for JavaScript. This code will redirect the current user to the Office 365 login page for authentication and then return an access token for reading information from SharePoint online. Listing 2 shows the complete code, which I will discuss.

Listing 2, JavaScript using adal.js

jQuery(function () {

    //authorization context
    var resource = 'https://[your tenancy]';
    var endpoint = 'https://[your tenancy]';

    var authContext = new AuthenticationContext({
        instance: '',
        tenant: '[your tenancy]',
        clientId: '[your client id]',
        postLogoutRedirectUri: window.location.origin,
        cacheLocation: 'localStorage'

    //sign in and out
    jQuery("#signInLink").click(function () {
    jQuery("#signOutLink").click(function () {

    //save tokens if this is a return from AAD

    var user = authContext.getCachedUser();
    if (user) {  //successfully logged in

        //welcome user
        jQuery("#loginMessage").text("Welcome, " + user.userName);

        //call rest endpoint
        authContext.acquireToken(resource, function (error, token) {

            if (error || !token) {
                jQuery("#loginMessage").text('ADAL Error Occurred: ' + error);

                type: 'GET',
                url: endpoint,
                headers: {
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + token,
            }).done(function (data) {
                jQuery("#loginMessage").text('The name of the SharePoint site is: ' + 
            }).fail(function (err) {
                jQuery("#loginMessage").text('Error calling REST endpoint: ' + 
            }).always(function () {

    else if (authContext.getLoginError()) { //error logging in
    else { //not logged in
        jQuery("#loginMessage").text("You are not logged in.");


The main object to deal with in adal.js is the AuthenticationContext. This object grants access to information about the current user and the application access tokens. When the application first runs, the user will not be logged in and the AuthenticationContext won’t have any real significance. You can see that the code calls the getCachedUser method to see if a valid user exists. If not, a message displays indicating that the user is not logged in.

Signing in to the application is done by clicking the appropriate link, which calls the login method. When this method is called, the user will be redirected to the Office 365 login page. After the login, they will be redirected back to the app along with an identifier token, which contains information about the user. This information is then used to welcome the user.

Once the user has logged in, the acquireToken method is called to get an access token for the application. This call will result in the application briefly redirecting and obtaining a token. This token is then used in a subsequent jQuery Ajax call to obtain the title of the root SharePoint online site. The name of the site is then displayed in the application.


The OAuth protocol can be complex to understand and implement. The Active Directory Authentication Library for JavaScript provides a good abstraction of the OAuth process for developers. The library makes it easy for developers to create applications that utilize RESTful services available through Azure Active Directory.

Topic: Security

Sign in with

Or register

  • Hello Scot,

    I am trying to get the adal approach working in my cordova app. But I think the problem is the redirectUrl. The error message states as reply address: ''''file://var/mobile/Containers/.. etcetera.
    Do you know how to deal with this?

    Kind regards,
  • Thanks for the great article.
  • Nice Article. I am dealing with AD which is not on Azure. Will Adal.js serve my purpose here?
  • Thank you so much for this article. However, I am having a bit of trouble reaching the API endpoint I am trying to query. The code simply never reaches that part of the code, but ends in line 38 saying "ADAL Error Occurred: AADSTS70005: response_type 'token' is not enabled for the application Trace ID: 827423a0-9d64-40dd-90f8-c01c2829036e Correlation ID: df263fcb-a1b2-44b9-9eb5-a23754f7e464 Timestamp: 2016-01-11 16:53:12Z" . The code displays "Welcome [email protected], but then changes to the above error message.

    In my case I am trying to query the endpoint at$top=10 , but the code never reaches that part of the code.

    Any ideas of why that happens?

    Again, thanks for this post - I really like your approach using jQuery in comparison to the much more complex examples using Angular.js out there :-).

  • qqqq
  • test
  • I'm not seeing that in mine. The article is a simplified version of a much bigger jQuery SPA application created by the Azure AD team. The germane JavaScript is located here:
  • Hi Scot,
    Thanks for article.
    One thing i noticed is that when the application logins for the first time, $.ajax executes twice (after callback from Azure AD). This results in execution of code in .done twice. Any idea why it's happening.