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

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

  • Digital Products

    Unlocking Business Potential: The Power of Custom Application Development

    Like any savvy business leader, you’re likely always on the lookout for tools to give your company a competitive edge. And in doing so, you’ve undoubtedly considered investing in custom application development. But the question is, how do you ensure that such a major investment in a custom web application development provides a strong return on […]

  • Digital Products

    Mastering Legacy Application Modernization: Strategies for Success

    The ironic truth of the business world is that change is the only constant. But this means that failing to keep pace with the competition and its technologies will only end with you falling behind. That’s where legacy application modernization enters the fold. When you modernize legacy applications, your team gains access to new features […]

  • Digital Products

    CTO Confessions Podcast

    In this episode of CTO Confessions, Rob Phillips, the Vice President of Software Engineering at UDig, digs into his journey from a passionate technologist in his youth to a seasoned leader in the tech industry. He shares valuable lessons on transitioning to senior leadership, the importance of understanding and articulating company problems, and the art of empowering teams for high performance.

  • Digital Products

    Navigating the Challenges of On Premise to Cloud Migration

    In today’s rapidly evolving technological landscape, the shift from on premise solutions to cloud-based infrastructure has become a pivotal transformation for organizations seeking to modernize their IT operations. This transition holds the promise of increased agility, cost savings, and enhanced scalability. However, it is not without its set of formidable challenges that organizations must navigate. […]

  • Digital Products

    The Power of Transferrable Skills in Tech Projects

    Every project has its own unique elements that require flexibility to be effective and achieve success. This often requires picking up new pieces of a tech stack, learning a new programming language, or a new project methodology. Fortunately, there are also many transferrable skills that carry over from one project to the next. In my […]

  • Digital Products

    The Four Pillars of Effective Digital Product Development

    In 2020 alone, approximately two billion consumers purchased at least one digital product. From software licenses to mobile apps and tech tools, consumers are becoming increasingly active in the digital product market, a trend that has naturally spurred brands across a wide range of industries to reevaluate their digital product design and development process workflows. […]