Thursday, May 2, 2019

Consuming Microsoft Graph in SharePoint Framework(SPFx)

In this blog I am sharing my experience of working with SPFx and Microsoft Graph API. I was pleasantly surprised how easy it was to get going with Microsoft Graph and I will show you with a demo how to consume Microsoft Graph from SharePoint Framework (SPFx) web part.


SPFx has now become the preferred way to create custom experiences on SharePoint online as well as On-Prem. I am not going to cover details on how to create and deploy SPFx web parts. If you are looking to get started on SPFx first go to https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-developer-tenant and then look up the SharePoint Developer Community channel on YouTube https://www.youtube.com/channel/UC_mKdhw-V6CeCM7gTo_Iy7w.

Microsoft Graph as I understand is a common API layer on top of all Microsoft Office 365 services like One Drive, SharePoint, Excel, Planner, Teams, Outlook, Azure Active Directory etc. It is just awesome because as an Office developer you can interact with all the above mentioned services and more with a common schema and a single access token. To know more graph API get started here https://developer.microsoft.com/en-us/graph/blogs/30daysmsgraph-day-1-why-you-should-learn-the-microsoft-graph/

Now that we have seen what is SPFx and Microsoft Graph, let me briefly explain the problem statement we will use to explore SharePoint framework and Microsoft Graph. Many organization like to manage access to SharePoint sites, Network folders, One drive documents etc. using Active Directory groups because these groups can be centrally managed and reused across applications. Usually it is not easy for business or power users to know exactly who are the members of these Active Directory groups. Our solution is to create a SPfx web part that can be used to display members of an Azure Active Directory Group. Power users can just add this web part to their SharePoint online site and view the members of the Azure Active Directory Groups.

If this if the first time you are building a SPFx web part then please first install the required tools, refer this: https://docs.microsoft.com/en-us/sharepoint/dev/spfx/set-up-your-development-environment

Lets build our solution, I am going to start with creating an SPFx web part by using the following command:
yo @microsoft/sharepoint
and I am going to select the option for  React JS


Lets open this folder using VS Code and you will see the typical SPFx folder structure created for you.


First Step: Dependencies
Since we know we are going to use query SharePoint site and Graph ensure dependencies for pnp graph and pnp sharepoint are included in the package.json file. You can get the dependencies from my code sample. Link to my code is available at the end of this blog.

Second Step: Graph Permissions
In our example we know we would like to read Azure AD groups and Users hence we will use Directory.Read.All permission scope. For identifying what permission scope is required you should always refer this article: 


In our project, open the config/package-solution.json and include the following permissions under the solution object:
"webApiPermissionRequests": [
     {
       "resource": "Microsoft Graph",
       "scope": "Directory.Read.All"
     }
   ]


Third Step: Get SP Context in the web part class file
Getting SPContext is a must without this you will not be able to access Graph.

We can get SPContext created this way
export default class AzureAdGroupViewerWebPart extends BaseClientSideWebPart<IAzureAdGroupViewerWebPartProps> {

  public onInit(): Promise<void> {
    pnpSetup({
      spfxContext: this.context
    });
    return Promise.resolve();
  }
  public render(): void {


Fourth Step: Component class
Now under the components folder you will find your component file as .tsx file
Here we need to make sure we import 
import { graph } from '@pnp/graph';
import { sp } from "@pnp/sp";


In my example I am using the Details List component from Office UI Fabric to display local SharePoint user groups and also members of a Azure Active Directory group. I strongly recommend using Office UI Fabric components because the look and feel matches with SharePoint theme and also it has been vetted by Office Developers community.

import {
  DetailsList,
  DetailsListLayoutMode,
  IColumn,
  IDetailsList
} from 'office-ui-fabric-react/lib/DetailsList';



To query SharePoint user group I have used pnp sp object. I am doing an ajax call to get a specific group using its name and the getting all users who are part of that group and saving that in the local state.

public componentDidMount(): void {
    sp.web.siteGroups.getByName(").users.get().then(users=>{
      this.setState({
        groups: users  
      });       
    }); 
  }


and the resulting grid looks like this:

You can see that this example SharePoint user group has many Azure AD groups as members. Now when we click on the button, we will query the Graph API and get users who are members of that Azure AD group, to do that we will call a function on button click:

1 onClick = (item,event) => {      
2    let gid = item.LoginName;
3    gid = gid.substr(gid.lastIndexOf("|") + 1, gid.length - gid.lastIndexOf("|"));
4    graph.groups.getById(gid).members.get().then(members => {   
5      this.setState({
6        grpMembers:members
7      }) 
8    });
9    event.preventDefault();   
10  }


In lines 2 and 3 in the above code snippet I am extracting the Azure Group's GUID and then using that to query graph API, once I get the members I save them to local state and I have another grid to display these users:



Code is available here : https://github.com/mahesh2005/SPFxWithGraph