Your Privacy

This site uses cookies to enhance your browsing experience and deliver personalized content. By continuing to use this site, you consent to our use of cookies.
COOKIE POLICY

Skip to main content

SharePoint and the Microsoft Graph | Part 2

SharePoint and the Microsoft Graph | Part 2
Back to insights

In part 1 of this series, we left off with configuring the proper application registration within our Azure Active Directory service. Ensuring the proper settings are in place will help alleviate headaches later on when we actually begin to implement our application.

One current issue with integrating the Microsoft Graph into SharePoint is the ability to properly authenticate the user against the application in Azure. Thankfully, there is a JavaScript library that does most of the heavy lifting for authentication.

My technique for including this library is to add it to the site’s master page. This allows the library to be available to any application without having to worry about extra code within the page using either the script editor or content editor.  You can also use the library (which is called the Active Directory Authentication Library, or ADAL) from this CDN:

https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.min.js

Here is a screenshot of the CDN located within my master page:

Now we need to integrate the proper scripts into our code to make our employee directory work properly. To do this, I planned on creating a single .js file and integrate that file into the page using the Content Editor Web Part.

Here is the first part of the code that requires information from the Azure application we registered:

(function () {

    "use strict";

var subscriptionId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";

//This variable requires the subscription ID from your actual Azure subscription (you can find a helpful tutorial about it here:

https://purerandomcode.wordpress.com/2015/04/17/how-to-azure-subscription-id-in-the-new-azure-portal/)

var clientId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx";

    //You need to place your Azure application’s application ID in the clientId variable.

  window.config = {

    subscriptionId: subscriptionId,                

    clientId: clientId,    

    postLogoutRedirectUri: window.location.origin,

    endpoints: {

      graphApiUri: 'https://graph.microsoft.com'

    },

    cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.

  };

  var authContext = new AuthenticationContext(config);  

  // Check For & Handle Redirect From AAD After Login

  var isCallback = authContext.isCallback(window.location.hash);

  authContext.handleWindowCallback();   

  if (isCallback && !authContext.getLoginError()) {

    window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);

  }

Here is the next part of the code, this should not need to be altered at all:

 

 

 

 

 

 

 

 

 

As you can see, towards the bottom of the code, there is a simple AJAX call to the graph API URI. Once we get to the success portion of our AJAX call, it works just like any other kind of AJAX call that you may use with the SharePoint REST API.

For example, here is the rest of the code that I used to implement my organization’s employee directory application:

var object = data.value;

          for (var i = 0; i < object.length; i++) {

            //Change '-' to '.' for both mobile numbers

            if(object[i].mobilePhone == null){

                var m2 = object[i].mobilePhone;

            }

            else{

            var m = object[i].mobilePhone;

            var m1 = m.toString();

            var m2 = m.replace(/-/g,'.');

            }

            //Change '-' to '.' for business numbers

            if(object[i].businessPhones == ''){

                var o2 = object[i].businessPhones;

            }

            else{

            var o = object[i].businessPhones;

            var o1 = o.toString();

            var o2 = o1.replace(/-/g,'.');

            }

            var name = object[i].displayName;

            var lowerName = name.toLowerCase();

            if(object[i].mail == null || object[i].jobTitle == null){

                //Do nothing

            }

                else {

            var employee = `

              <span class="listSearch"><div class="ms-Grid-col ms-sm12 ms-md6 ms-lg6 ms-xl6 ms-xxl4 empCard">

              <div class="cardContent">

                <p class="empName" style="line-height:1.2;" id="`+ lowerName +`"><span style="display:none">` + lowerName + `</span> `+

object[i].displayName +`<br/>

                <span class="jobTitle">`+ object[i].jobTitle +`</span></p>

                <p class="empLocation">`+ object[i].officeLocation +`</p>

                <p style="line-height:100%">

                    O: <span class="empPhone"><a href="tel:`+ o2 +`">`+o2+`</a></span><br/>

                    M: <span class="empPhone"><a href="tel:`+ m2 +`">`+ m2 +`</a></span><br/>

                    E: <span class="empPhone"><a href="mailto:`+ object[i].mail +`">`+ object[i].mail +`</a></span>

              </p></div></div></span>

            `;

            $('#employeeDirectory').append(employee);

          }     

          }

      },

    }).fail(function () {

      console.log('Fetching files from AD Failed.');

    });

I placed some extra code for formatting the phone numbers the right way as well as placing the ability to filter names based on a string entered into a search box on the page. The expanded form of this code is found on my GitHub page here:

https://github.com/talon2king/EmployeeDirectoryTutorial

Here is a view of what my organization’s employee directory looks like fully implemented (information has been blurred on purpose):

Here is the view of the same directory from a mobile phone:

The code that I used was an adaptation of the code found here:
https://nickvandenheuvel.eu/2016/01/06/authenticate-an-office-365-user-with-adal-js

Digging In

  • Software Engineering

    When There’s Too Much to Fix: How Smart Prioritization Unlocks Revenue at Scale

    Every operations team has a backlog. The question isn’t whether you can clear it — it’s whether you’re clearing it in the right order. For most teams, the honest answer is no. And that gap between the order work gets done, and the order it should get done is quietly costing organizations millions. The Volume Problem High-volume exception processing shows up across […]

  • Software Engineering

    Creating Reusable Code Templates to Reduce Client Project Startup Time

    In consulting, one of the least visible but most expensive phases of a project is the beginning. Teams can spend days or weeks setting up repositories, agreeing on structure, wiring basic infrastructure, and solving problems that have already been solved many times before. Code templates are a practical way to reduce overhead while improving consistency. […]

  • Software Engineering

    Player Three Has Entered the Game: How AI Is Finally Bridging the Divide Between Design and Engineering

    As AI begins to become more prominent in our day-to-day lives, I find myself in a unique position. As a practicing software engineer and UI/UX designer, I am genuinely happy to see the introduction of AI tools begin to take shape in our industry. But more importantly, I am happy to start seeing the effects it is having on what has historically been a pretty challenging relationship: the […]

  • Software Engineering

    The Disappearing Middle of Software Work: Why the Bookends – Strategy & Impact – Matter Most Now

    Here’s a question nobody in enterprise software wants to sit with: what happens to the middle? Not the middle of the org chart. The middle of the work. The vast, expensive layer of effort that has defined enterprise software delivery for thirty years—translating what the business wants into working code. The requirements-to-implementation pipeline. The “build phase.” […]

  • Software Engineering

    Zero-Code Telemetry with OpenTelemetry’s OBI

    Full distributed tracing and exception capture for any application — without writing a single line of instrumentation code. View the source code on GitHub → The Premise Observability is essential for understanding what’s happening inside your services, but instrumenting an application by hand — adding trace spans, logging calls, and metric counters throughout your codebase […]

  • Software Engineering

    Building a Consultant in the Trenches: How Playing Offensive Line Shaped My Consulting Career

    People often ask me the same question when they find out that I played college football: “Do you miss it?” On the surface, it’s a bad question with an obvious answer. Yes. However, if I give myself a minute to sit with that question, the answer is more nuanced. Yes, I miss playing football, but […]