28
Jan
2019
Microsoft Graph with SharePoint Framework

In our previous blog, we have covered the basic knowledge about Microsoft Graph and Azure Active Directory Graph API. From this blog, let’s have some more knowledge about consuming Microsoft Graph APIs secured with Azure AD for SharePoint development.

SharePoint Framework (starting from v.1.4.1) can be used to consume Microsoft Graph APIs secured with Azure AD. This section of the blog gives an overview of how to consume Microsoft Graph API in a SharePoint Framework solution using custom permissions.

Let’s search users based on their name in the current tenant using Microsoft Graph API with SharePoint Framework in the below example. Here, a client-side SPFx web part is used to get the inputs from an end user and the MS Graph API is used to search a user based on the provided inputs from the end user. The searched result output contains all the matching names through Office UI Fabric component DetailsList.

Create a SharePoint Framework solution

Ensure you are using SharePoint Framework generator v.1.4.1 or later in your environment. If you are running an old version, you need to update framework version to 1.4.1 or later using below command.

npm install -g @microsoft/generator-sharepoint

  • Create a new project directory named spfx-api-scopes in your favorite location by following Step 2 – To Create SPFx web part from this link.
  • When scaffolding is completed, start Visual Studio code using below command.

    code

    Node.js Command Prompt

Configure initial elements

Create custom properties to use in the client-side web part.

  • Create a source code file named ClientMode.ts inside src/webparts/graphConsumer/components folder of the solution.

Create source file

  • Declare a TypeScript enum for ClientMode property of web part inside ClientMode.ts file.
  • ClientMode.ts
    export enum ClientMode {
        aad,
        graph,
    }
  • Inside GraphConsumerWebPart.ts file (path: \src\webparts\graphConsumer\GraphConsumerWebPart.ts), modify IGraphConsumerWebPartProps interface to include ClientMode.
  • GraphConsumerWebPart.ts
    export interface IGraphConsumerWebPartProps {
     clientMode: ClientMode;
    }
  • Change getPropertyPaneConfiguration() method for property-pane choice selections.
  • GraphConsumerWebPart.ts
    protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
        return {
            pages: [
              {
                  header: {
                      description: strings.PropertyPaneDescription
                  },
                  groups: [
                    {
                        groupName: strings.BasicGroupName,
                        groupFields: [
                          PropertyPaneChoiceGroup('clientMode', {
                              label: strings.ClientModeLabel,
                              options: [
                                { key: ClientMode.aad, text: "AadHttpClient"},
                                { key: ClientMode.graph, text: "MSGraphClient"},
                              ]
                          }),              
                        ]
                    }
                  ]
              }
            ]
        };
    }
  • Also, you will need to update the render method to create an instance of React component to render client mode choices.
  • GraphConsumerWebPart.ts
    public render(): void {
        const element: React.ReactElement<IGraphConsumerProps > = React.createElement(
          GraphConsumer,
          {
              clientMode: this.properties.clientMode,
              context: this.context,
          }
        );
     
    ReactDom.render(element, this.domElement);
    }
  • Add below import statements at the top of the GraphConsumerWebPart.ts file to import PropertyPaneChoiceGroup control and ClientMode enum.
  • GraphConsumerWebPart.ts
    import * as React from 'react';
    import * as ReactDom from 'react-dom';
    import { Version } from '@microsoft/sp-core-library';
    import {
     BaseClientSideWebPart,
     IPropertyPaneConfiguration,
     PropertyPaneChoiceGroup
    } from '@microsoft/sp-webpart-base';
     
    import * as strings from 'GraphConsumerWebPartStrings';
    import GraphConsumer from './components/GraphConsumer';
    import { IGraphConsumerProps } from './components/IGraphConsumerProps';
    import { ClientMode } from './components/ClientMode';

Update resource strings

  • Rewrite the interface in mystrings.d.ts file inside src/webparts/graphConsumer/loc folder to compile the solution.
  • mystrings.d.ts
    declare interface IGraphConsumerWebPartStrings {
        PropertyPaneDescription: string;
        BasicGroupName: string;
        ClientModeLabel: string;
        SearchFor: string;
        SearchForValidationErrorMessage: string;
    }
  • Update en-us.js file in the same folder to configure values for resource strings.
  • en-us.js
    define([], function () {
        return {
            "PropertyPaneDescription": "Description",
            "BasicGroupName": "Group Name",
            "ClientModeLabel": "Client Mode",
            "SearchFor": "Search for",
            "SearchForValidationErrorMessage": "Invalid value for 'Search for' field"
        }
    });

Apply style for client-side web part

You will need to update SCSS style file

  • Add following styles in GraphConsumer.module.scss under src/webparts/graphConsumer/components folder.
  • GraphConsumer.module.scss
    .form {
        @include ms-font-l;
        @include ms-fontColor-white;
      }
     
      label {
        @include ms-fontColor-white;
      }

Configure React component

Modify GraphConsumer component under src/webparts/graphConsumer/components folder.

  • Edit IGraphConsumerProps.ts file to include the custom properties by importing ClientMode enum and WebPartContext type.
  • IGraphConsumerProps.ts
    import { WebPartContext } from '@microsoft/sp-webpart-base';
    import { ClientMode } from './ClientMode';
     
    export interface IGraphConsumerProps {
        clientMode: ClientMode;
        context: WebPartContext;
    }
  • IUserItem interface file defines users fetched from the tenant and it is inside the components folder.
  • IUserItem.ts
    export interface IUserItem {
        displayName: string;
        mail: string;
        userPrincipalName: string;
    }
  • Create a new file IGraphConsumerState.ts inside components folder to add a new interface for React component. Import IUserItem interface in IGraphConsumerState.ts state file under components folder.
  • IGraphConsumerState.ts
    import { IUserItem } from './IUserItem';
     
    export interface IGraphConsumerState {
        users: Array<IUserItem>;
        searchFor: string;
    }
  • Add required import statements in GraphConsumer.tsx file.
  • GraphConsumer.tsx
    import * as React from 'react';
    import styles from './GraphConsumer.module.scss';
    import * as strings from 'GraphConsumerWebPartStrings';
    import { IGraphConsumerProps } from './IGraphConsumerProps';
    import { IGraphConsumerState } from './IGraphConsumerState';
    import { ClientMode } from './ClientMode';
    import { IUserItem } from './IUserItem';
    import { escape } from '@microsoft/sp-lodash-subset';
     
    import {
     autobind,
     PrimaryButton,
     TextField,
     Label,
     DetailsList,
     DetailsListLayoutMode,
     CheckboxVisibility,
     SelectionMode
    } from 'office-ui-fabric-react';
     
    import { AadHttpClient, MSGraphClient } from "@microsoft/sp-http";
  • Outline column definition for the DetailsList Office UI Fabric component after the import statements.
  • GraphConsumer.tsx
    let _usersListColumns = [
     {
         key: 'displayName',
         name: 'Display name',
         fieldName: 'displayName',
         minWidth: 50,
         maxWidth: 100,
         isResizable: true
     },
     {
         key: 'mail',
         name: 'Mail',
         fieldName: 'mail',
         minWidth: 50,
         maxWidth: 100,
         isResizable: true
     },
     {
         key: 'userPrincipalName',
         name: 'User Principal Name',
         fieldName: 'userPrincipalName',
         minWidth: 100,
         maxWidth: 200,
         isResizable: true
     },
    ];
  • Update render() method with the below code.
  • GraphConsumer.tsx
    public render(): React.ReactElement<IGraphConsumerProps> {
        return (
          <div className={ styles.graphConsumer }>
           <div className={ styles.container }>
             <div className={ styles.row }>
               <div className={ styles.column }>
                 <span className={ styles.title }>Search for a user!</span>
                 <p className={ styles.form }>
                   <TextField 
                       label={ SearchFor } 
                       required={ true } 
                       value={ this.state.searchFor }
                       onChanged={ this._onSearchForChanged }
                       onGetErrorMessage={ this._getSearchForErrorMessage }
                     />
                 </p>
                 <p className={ styles.form }>
                   <PrimaryButton 
                       text='Search' 
                       title='Search' 
                       onClick={ this._search } 
                     />
                 </p>
                 {
                   (this.state.users != null && this.state.users.length > 0) ?
                     <p className={ styles.form }>
                     <DetailsList
                         items={ this.state.users }
                         columns={ _usersListColumns }
                         setKey='set'
                         checkboxVisibility={ CheckboxVisibility.hidden }
                         selectionMode={ SelectionMode.none }
                         layoutMode={ DetailsListLayoutMode.fixedColumns }
                         compact={ true }
                     />
                   </p>
                   : null
                 }
               </div>
             </div>
           </div>
         </div>
       );
    }
  • Change React component type as shown below.
  • GraphConsumer.tsx
    export default class GraphConsumer extends React.Component<IGraphConsumerProps, IGraphConsumerState> {
     
        constructor(props: IGraphConsumerProps, state: IGraphConsumerState) {
          super(props);
     
            // Initialize the state of the component
            this.state = {
                users: [],
                searchFor: ""
            };
        }
  • Handle events for TextField component and validations for search criteria.
  • GraphConsumer.tsx
    @autobind
    private _onSearchForChanged(newValue: string): void {
     
        // Update the component state accordingly to the current user's input
        this.setState({
            searchFor: newValue,
        });
    }
     
    private _getSearchForErrorMessage(value: string): string {
        // The search for text cannot contain spaces
        return (value == null || value.length == 0 || value.indexOf(" ") < 0)
          ? ''
          : `${SearchForValidationErrorMessage}`;
    }
  • Add below code to examine client technology for consuming Microsoft Graph.
  • GraphConsumer.tsx
    @autobind
    private _search(): void {
    // Based on the clientMode value search users
        switch (this.props.clientMode)
        {
        case ClientMode.aad:
            this._searchWithAad();
            break;
        case ClientMode.graph:
            this._searchWithGraph();
            break;
        }
    }

Configure the API permissions requests

You need to explicitly mention the permission requirements in the solution manifest file in order to consume Microsoft Graph API.
To achieve this, configure webApiPermissionRequests in package-solution.json file under config folder

package-solution.json
{
    "$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
    "solution": {
        "name": "spfx-api-scopes-client-side-solution",
        "id": "b13889b9-2455-4c4b-894b-a951b4fd5d27",
        "version": "1.0.0.0",
        "includeClientSideAssets": true,
        "skipFeatureDeployment": true,
        "webApiPermissionRequests": [
        {
          "resource": "Microsoft Graph",
          "scope": "User.ReadBasic.All"
        }
    ]
  },
  "paths": {
      "zippedPackage": "solution/spfx-api-scopes.sppkg"
  }
}

webApiPermissionRequests item defines the resource and scope of permission request. The resource can be name or Azure AD ObjectId for which to configure permission request. Microsoft Graph is the resource for consuming Microsoft Graph capabilities. The scope defines the type of the permission or its unique ID.

You can use User.ReadBasic.All permission to search users and get user properties such as displayName and mail.

Consume Microsoft Graph

You can use two ways to consume Microsoft Graph:

  • AadHttpClient client object: used to consume Microsoft Graph or any other REST API
  • MSGraphClient client object: used to consume Microsoft Graph only.

AadHttpClient client object

  • Call context.aadHttpClientFactory.getClient() method to create a new instance of AadHttpClient client object.
  • Insert below _searchWithAad() method inside GraphConsumer class in the sample solution
  • GraphConsumer.tsx
    private _searchWithAad(): void {
    // Using Graph here, but any 1st or 3rd party REST API that requires Azure AD auth can be used here.
    this.props.context.aadHttpClientFactory
      .getClient('https://graph.microsoft.com')
      .then((client: AadHttpClient) => {
          // Search for the users with givenName, surname, or displayName equal to the searchFor value
          return client
            .get(
              `https://graph.microsoft.com/v1.0/users?$select=displayName,mail,userPrincipalName&$filter=(givenName%20eq%20'${escape(this.state.searchFor)}')%20or%20(surname%20eq%20'${escape(this.state.searchFor)}')%20or%20(displayName%20eq%20'${escape(this.state.searchFor)}')`,
            AadHttpClient.configurations.v1
          );
      })
    .then(response => {
        return response.json();
    })
          .then(json => {
     
              // Prepare the output array
              var users: Array<IUserItem> = new Array<IUserItem>();
    // Map the JSON response to the output array
    json.value.map((item: any) => {
        users.push( {
            displayName: item.displayName,
            mail: item.mail,
            userPrincipalName: item.userPrincipalName,
        });
    });
     
    // Update the component state accordingly to the result
    this.setState(
      {
          users: users,
      }
    );
    })
          .catch(error => {
              console.error(error);
    });
    }

MSGraphClient client object

You can utilize MSGraphClient object to target Microsoft Graph.
Insert below _searchWithGraph() method inside GraphConsumer class in the sample solution.

GraphConsumer.tsx
private _searchWithGraph(): void {
 
this.props.context.msGraphClientFactory
  .getClient()
  .then((client: MSGraphClient): void => {
      // From https://github.com/microsoftgraph/msgraph-sdk-javascript sample
      client
        .api("users")
        .version("v1.0")
        .select("displayName,mail,userPrincipalName")
        .filter(`(givenName eq '${escape(this.state.searchFor)}') or (surname eq '${escape(this.state.searchFor)}') or (displayName eq '${escape(this.state.searchFor)}')`)
      .get((err, res) => {  
 
          if (err) {
              console.error(err);
              return;
}
// Prepare the output array
var users: Array<IUserItem> = new Array<IUserItem>();
// Map the JSON response to the output array
res.value.map((item: any) => {
    users.push( { 
        displayName: item.displayName,
        mail: item.mail,
        userPrincipalName: item.userPrincipalName,
    });
});
// Update the component state accordingly to the result
this.setState(
  {
      users: users,
  }
);
});
});
}

Deploy the solution

You’re now done to build and deploy the solution.

  • Run the gulp commands to build the solution.

    gulp build

gulp build

  • Bundle and package your solution.

    gulp bundle

    gulp bundle
    gulp package-solutiongulp package-solution

  • Upload the solution package (.sppkg file) from sharepoint/solution folder of your project directory to the app catalog of your tenant.

Upload the solution package

  • Once you upload the package in “Apps for SharePoint”, a message at the bottom of the screen conveys that the package requires permissions. This is because of the webApiPermissionRequests property where we mentioned “Microsoft Graph” as a resource and “User.ReadBasic.All” as the scope in package-solution.json file. Click Deploy.

webApiPermissionRequests

  • Navigate to the SharePoint Admin Center and choose Try the preview from the upper right hand corner.

SharePoint Admin Center

  • Select API management under Advanced in the quick launch menu.

Select API managementSharePoint Online admin of your tenant can approve or deny any pending permission approval request. You cannot view the solution package which requests the permission though.

  • Select the permission requested inside package-solution.json file and choose Approve or reject.

Choose Approve or Reject.

  • Click Approve from Approve or reject access panel to provide access.

Select Approve

  • Once successfully approved, you are now ready to test your solution.

Test the solution

  • Execute below gulp command to run your solution.

    gulp serve –nobrowser

gulp serve –nobrowser

  • Open the browser and navigate to the SharePoint Framework Workbench page for your tenant.

    https://<your-tenant>.sharepoint.com/_layouts/15/Workbench.aspx


  • Add the newly configured GraphConsumer client-side web part.

Configured GraphConsumer

  • Set ClientMode from properties, either AadHttpClient or MSGraphClient and search for users.

AadHttpClient as ClientModeMSGraphClient as ClientMode

 

Done! This way you can consume Microsoft Graph APIs in SharePoint Framework.

Conclusion

Using Microsoft Graph API, the Azure AD resources are accessed to provide searched users in a secure manner. Multiple APIs can be used from Office 365 and other Microsoft cloud services through a single endpoint i.e. Microsoft Graph (https://graph.microsoft.com). Microsoft Graph supports to access data from multiple Microsoft Cloud Services including Azure AD, SharePoint, MS Planner, MS Teams, etc.

26
Dec
2018
Microsoft Graph and Azure Active Directory Graph API

One question that comes to our mind while require accessing Azure Active Directory resources is whether we should make use of Microsoft Graph (graph.microsoft.com) or Azure AD Graph (graph.windows.net). More commonly, Microsoft recommends using Microsoft Graph instead of Azure AD Graph API to access directory-based features, as Azure AD Graph API may fit in for very few scenarios.
Azure AD Graph API

Two APIs, different functionality

Microsoft Graph supports most of the Azure AD Graph features, but not all. Also, Microsoft Graph supports some features which are not in Azure AD graph, e.g. $select projection queries.

Microsoft aims to close the gap between Microsoft Graph and Azure AD Graph features by making it comfortable for developers to use Microsoft Graph. Now onwards, users who are building new apps or integrating existing apps with cloud will be proposed to use Microsoft Graph.

Note: Apps already using Azure AD Graph won’t get affected and Azure AD Graph API will remain fully functional for those applications.

While Azure AD Graph client library is only available for .Net applications, Microsoft Graph client libraries support multiple platforms and languages, which gives you more choices to use directory data in your apps.

Microsoft Graph – An API for Microsoft 365

Microsoft Graph provides a programming model to connect Office 365, Windows 10, Azure Active Directory, and Enterprise Mobility and Security services. Microsoft Graph is used to build apps for users interacting with millions of data by accessing resources using a single endpoint: https://graph.microsoft.com

It is a RESTful Web API that allows you to access cloud services. You can request Microsoft Graph API after registering an app with Azure AD and accessing authentication tokens for a user.

You can use REST APIs and client libraries exposed by Microsoft Graph to connect data on:

  • Office 365 services: SharePoint, Microsoft Teams, Planner, Outlook/Exchange, Excel, OneDrive and OneNote.
  • Windows 10 services
  • Azure Active Directory
  • Enterprise Mobility + Security services: Advanced Threat Analytics, Advanced Threat Protection, Identity Manager and Intune

Microsoft Graph uses relationships to connect resources under these services. For example, member of relationship can be used to connect a user to a group and using manager relationship, a user can be connected to another user.

You can get important insights about the data using Microsoft Graph. For example, you can get the most accessed files that are trending around a user.

Microsoft Graph

You can construct a request to read from or write to a resource from services using:
https://graph.microsoft.com/{version}/{resource}?query-parameters

1) Below are the components of Microsoft Graph API request:

> HTTP Method used for making request to Microsoft Graph

Method Description
GET Get data from the resource
POST Create a new resource
PATCH Modify resource with the latest values
PUT Replace resource with a new one
DELETE Delete a resource
  • No request body is needed for GET and DELETE methods
  • The Request body is required for PATCH, POST and PUT methods. It is returned in JSON format containing additional information such as values for properties.

> Version: Microsoft Graph API version which your app is using

Version Description
v1.0 Contains commonly available APIs. Most recommended for production apps
beta Contains APIs in the preview stage. Recommended for development or test apps, not to be used for production apps.

> Resource: Microsoft Graph resource with which you are interacting inside the request URL.

  • Top-level resources include me, sites, users, groups and drives
  • Most of the top-level resources contain relationships used to access other resources such as me/messages and me/drive
  • You can also use methods to interact with resources such as me/sendEmail.

> Query-parameters (optional): A set of parameters to customize request or response like filter response matching a custom query. For example, below filter parameter returns messages for a user with specified emailAddress only.
https://graph.microsoft.com/v1.0/me/messages?filter=emailAddress eq ‘abc.xyz@company.com’

2) Below are the components returned in response to your request:

  • HTTP status code: Standard HTTP status code returned in terms of success or failure.
    Some of the commonly returned status codes in case of failure include
  • Status code Status message Description
    400 Bad request Unable to process the request as it is incorrect/malformed
    401 Unauthorized Missing or invalid authentication information
    403 Forbidden Access denied because the user does not have required permission
    404 Not found Requested resource is not available
  • Response message: Data or result requested.
  • Next link: In the case of the response containing a lot of data, you can navigate to the next page by selecting Next. It happens while using server-side paging or due to the usage of $top query parameter to limit the number of results returned on a page.
    https://graph.microsoft.com/v1.0/users?$top=3

Microsoft Graph API Features

You can use Microsoft Graph to add value to your application and build friendly user context experiences.

  • Simplifies user onboarding by automating tasks. Activities carried out include – assign managers, assign roles to users, provide permissions to documents, assign product licenses, change users’ roles and much more.
  • Retrieves Excel workbook data and builds powerful workflows to integrate data collection with cloud services such as SharePoint.
  • Allows finding meeting times and provides profile information for one or more attendees.
  • Gets recommended meeting times by scanning your calendar containing attendees and their preferred timeslots.
  • Supports file format conversion to PDF. Office file types such as Word, Excel, and PowerPoint as well as other common formats such as CSV and RTF can be converted.
  • Manages employee profiles by keeping your company Azure directory up-to-date. It can also modify user profile information stored in SharePoint via API.
  • Sends you a notification by subscribing to changes in your calendar, when you spend too much time in meetings and suggests meetings which you can miss based on the relevancy of your attendees.
  • Helps you sync and sort out personal data on your phone.
  • Calls Security Alerts API to avoid threats and correlates alerts from data sources in a simplified way.

Some of the common Microsoft Graph API requests include

Request Endpoint URL
Get my profile https://graph.microsoft.com/v1.0/me
Get my photo https://graph.microsoft.com/v1.0/me/photo/$value
Get my files https://graph.microsoft.com/v1.0/me/drive/root/children
Get my email https://graph.microsoft.com/v1.0/me/messages
Get my calendar events https://graph.microsoft.com/v1.0/me/events
Get my manager https://graph.microsoft.com/v1.0/me/manager

 

Azure Active Directory Graph API

The Azure Active Directory (Azure AD) Graph API is used to access Azure AD objects using REST API OData endpoints. You can use Azure AD Graph API in your applications to perform CRUD operations on Azure AD data and objects.
Some of the common operations supported by Azure AD Graph API include:

  • Create a new user in Azure AD
  • Get properties of a user such as a group/s user belongs to, their email address or location
  • Update properties of a user, such as location, password or phone number
  • Disable or delete the user account

Similarly, you can access other Azure objects such as groups and applications.

Before you call Azure AD Graph API on a directory, you must register your app with Azure AD. You must also consent your app to access Azure AD Graph API.

Features of Azure AD Graph API

  • REST API Endpoints: Azure AD Graph API comprises of REST API OData endpoints that are accessed using HTTP requests. Azure AD Graph API’s requests and responses support XML or JSON formats.
  • Authentication with Azure AD: Azure AD Graph API request appends a JSON Web Token (JWT) in its authentication header. You can acquire the token by requesting Azure AD’s token endpoint.
  • Role-Based Authorization (RBAC): Azure AD Graph API uses security groups to perform Role-Based Authorization. For example, you can call Check Group Membership Boolean operation in your application to check user’s access to the specific resource.
  • Differential Query: Differential query tracks changes in a directory between two durations without the need to fire independent queries to API, which returns modifications made between the previous differential request and active request.
  • Directory Extensions: You can use custom properties with Azure directory objects to access properties from the external data source such as Skype.
  • Secured by permission scopes: Using Azure AD Graph API, you can use permission scopes to enable secure access to directory data using OAuth 2.0. It supports two types of permissions:
    > Delegated permission: Users are given delegated access to data through authorization from the signed-in user.
    > Application permissions: Users are given role-based access control defined by the application without authorization from the signed-in user.

Your client apps can utilize both delegate and application permission scopes exposed by Azure AD Graph API.

Constructing Azure AD Graph API URL

To perform CRUD operations on Azure directory and resources through Graph API, you can make use of Open Data (OData) protocol-based URLs.
Below are the components used in the URL of Graph API
https://graph.windows.net/{tenant-identifier}/{resource-path}?[query-parameters]

  1. Service Root: https://graph.windows.net
  2. Tenant identifier: It can be a verified domain name or a tenant object ID registered with Azure AD
  3. Resource path: It identifies Azure AD resources or entities, for example, users and groups, to be interacted with. You can also access a specific entity from within the top-level entity, for example, users/{objectId} or users/userPrincipalName
  4. Query parameters: The part of the Graph API URL after question mark (?) form the query parameters section. Note that the “api-version” query parameter is mandatory on all requests made via Graph API. Other query options supported by Azure AD Graph API include $filter, Stop, $orderby, $format and $expand. You can find more information regarding query parameters here: https://msdn.microsoft.com/Library/Azure/Ad/Graph/howto/azure-ad-graph-api-supported-queries-filters-and-paging-options

Graph API versions

You must pass the version of operation inside query string parameter “api-version”. Without an api-version, your request will be rejected and you will receive an error “The specified api-version is invalid”.

Graph API versions

  • You use numerical value for api-version 1.5 or later api-version 1.6.
  • For using earlier versions, you used data string of the format YYYY-MM-DD i.e. api-version=2014-12-07
  • In the case of preview features, you will need to use “beta” i.e. api-version=beta

Graph API metadata

To retrieve metadata file simply add $metadata after the tenant identifier in the URL. For example, enter below URL I browser to return Azure AD Graph API metadata file for a tenant.

https://graph.windows.net/tenantname/$metadata?api-version=1.6

Note: Replace the yellow highlighted tenantname and useraccount words based on your tenant name and user account respectively.
The metadata file returns described entities and their object types, actions, and functions exposed by thepassed Graph API version.

Graph API metadata

 

Azure AD Graph API common queries

Some of the common queries performed with Azure AD Graph include accessing top-level resources and other specific entities below top-level resource. Ensure that a valid authentication header having valid bearer token will be required to access Azure AD Graph API across the tenant.

Querying top-level resources

Top-Level Resource Query Results URI
Top-level resources Returns list of URIs for top-level resources for Azure AD https://graph.windows.net/tenantname?api-version=1.6
Company information Retrieves company/tenant information https://graph.windows.net/tenantname/tenantDetails?api-version=1.6
Contacts information Retrieves contact information for an organization https://graph.windows.net/tenantname/contacts?api-version=1.6
Users Retrieves user information https://graph.windows.net/tenantname/users?api-version=1.6
Groups Retrieves group data https://graph.windows.net/tenantname/groups?api-version=1.6
Directory Roles Retrieve AD tenant roles https://graph.windows.net/tenantname/directoryRoles?api-version=1.6
SubscribedSkus Retrieves all the subscriptions of the tenant https://graph.windows.net/tenantname/subscribedSkus?api-version=1.6
Directory metadata information Retrieves tenant’s AD metadata file describing entities and their object types and data model https://graph.windows.net/tenantname/$metadata?api-version=1.6

 

Other query operations
Some of the additional commonly used Graph API queries include:

Query operation URI
Fetch users and groups https://graph.windows.net/tenantname/users?api-version=1.6
https://graph.windows.net/tenantname/groups?api-version=1.6
Retrieve user using objectId or userPrincipalName https://graph.windows.net/tenantname/users/f3d5fba2-d5b7-45f7-aedd-6b2efa5bf1cd?api-version=1.6 https://graph.windows.net/tenantname/users/useraccount?api-version=1.6
Retrieve or filter user where displayName equal to a specific value https://graph.windows.net/tenantname/users?$filter=displayName eq ‘Tom Datson’&api-version=1.6
Retrieve or filter user where firstName equal to a specific value https://graph.windows.net/tenantname/users?$filter=givenName eq ‘Tom’&api-version=1.6
Retrieve or filter user based on givenName and surname https://graph.windows.net/tenantname/users?$filter=givenName eq ‘Tom’ and surname eq ‘Datson’&api-version=1.6
Fetch group by objectId https://graph.windows.net/tenantname/groups/164c55e3-2b44-4429-aac1-0f538e75ac05?api-version=1.6
Retrieve manager of a user https://graph.windows.net/tenantname/users/useraccount/manager?api-version=1.6
Retrieve direct reports list for a user https://graph.windows.net/tenantname/users/ff9661e4-cdae-41da-847a-b0fdb753fea0/directReports?api-version=1.6
Get links direct reports lists for a user https://graph.windows.net/tenantname/users/ff9661e4-cdae-41da-847a-b0fdb753fea0/$links/directReports?api-version=1.6
Retrieve group membership list https://graph.windows.net/tenantname/groups/bc439c50-abf6-4946-9307-b0061b73ab5b/members?api-version=1.6
Retrieve membership of user https://graph.windows.net/tenantname/users/b2631075-c011-4175-8584-0952e898fee2/memberOf?api-version=1.6
Retrieve all the groups that a user is member of https://graph.windows.net/tenantname/users/b2631075-c011-4175-8584-0952e898fee2/$links/memberOf?api-version=1.6
Retrieve all the groups with displayName >= ‘ab’ and <= ‘cd’ https://graph.windows.net/tenantname/groups?$filter=displayName ge ‘ab’ and displayName le ‘cd’&api-version=1.6
Retrieve all local account users in Azure AD https://graph.windows.net/tenantname/users?filter=creationType eq ‘LocalAccount’&api-version=1.6
Retrieve local account user with a specified sign-in name from Azure AD https://graph.windows.net/tenantname/users?$filter=signInNames/any(x:x/value eq ‘useraccount’)&api-version=1.6

 
Azure AD Graph Explorer

To query Azure directory data using Azure Graph API in your application, you can use Azure AD Graph explorer. Navigate to https://graphexplorer.azurewebsites.net/ to load Azure AD Graph Explorer. Sign-in with your Azure AD account to access Azure AD Graph Explorer.
Note: You or your tenant admin will need to consent during sign-in. In case of an Office 365 subscription, you are automatically consenting to Azure AD tenant.
Enter below URL to display all the users inside signed in user’s tenant directory.
https://graph.windows.net/tenantname/users?api-version=1.6

Azure AD Graph Explorer

Similarly, to get the list of all groups in your directory, type below query in the request text box and click on Go button
https://graph.windows.net/tenantname/groups?api-version=1.6
Some of the features of Azure AD Graph Explorer include:

  • Request history
  • ‘me’ and ‘myorganization’ addressing aliases are supported.
  • All the CRUD operations POST, GET, PATCH and DELETE are supported against your tenant
  • Troubleshooting of issues while running queries using response headers.
  • Response to query in JSON format with the expand and collapse functionalities

Although, there is no support to display a thumbnail picture in Azure AD Graph Explorer. In order to fetch and upload user’s profile picture, you can use Fiddler Web Debugger.
You can install Fiddler using link http://www.telerik.com/fiddler

Difference between Azure AD Graph API and Microsoft Graph API

Microsoft Graph API supports most, but not all features supported by Azure AD Graph API

Feature Azure AD Graph capability Microsoft Graph capability
Endpoint https://graph.windows.net https://graph.microsoft.com
Delta Sync Differential query/delta sync available for users and groups • General Availability with Delta query

• Organizational contacts delta sync is not supported.

• Sync from now is still not supported

Organizational Contact Resource Type Supported In preview stage
Applications Management Applications management such as

• Application and service principal entity types

• Assigning applications to users and groups

• Assigning OAuth permissions to applications

Available in preview
Partner Admin support Yes General Availability
Domain resource type Yes General Availability
Contracts resource type Yes General Availability
Directory schema extension definition registration Supported General availability.

Supports extending resources with application data.

Does not support application or service principal resource type

Batching Yes Available in preview
Properties Properties are missing on user

resources such as sipProxyAddress,

otherEmails, licenseDetails

General availability.
OtherEmails still not supported, but planned for future
Get Object GetObjectsByObjectsIds method General availability. getByIds method
Check Membership IsMemberOf method Unplanned. Need to use checkMemberGroups method
Users Management Users management in B2C tenant Coming soon in preview

 
Conclusion

Microsoft is recommending to use Microsoft Graph instead of Azure Active Directory Graph API to access Azure AD resources. Microsoft development is mainly focused on Microsoft Graph and there is no further extension planned for Azure AD Graph API. In our next blog, we will see how we can consume Microsoft Graph APIs secured with Azure AD in SharePoint Framework.

12
Dec
2018
Microsoft Recurrence Flow for Office 365

Huge organizations have many requirements for the automation of tasks in one or another way. It is always beneficial for an organization to have some automated tasks because it reduces manual efforts of people. Some organizations or users have requirements to send the notification, alerts, etc. on a timely basis from SharePoint Online. As one can’t deploy the custom coded solution in SharePoint Online, Microsoft is provisioning Microsoft Azure Web Job and Microsoft Flow to achieve these type of requirements.

Microsoft Azure Web Job runs a program or script in the background in the same context of the Web app, API app or Mobile app. To use Azure Web Job, the Azure subscription is must require. After this, multiple Web Jobs can be created and used. A web job can be scheduled to run in a timely manner (hourly, daily, etc.) or it can be triggered on a specific event like item update, file upload, etc.

Microsoft Flow is a tool which is cloud-based software and allows users to create automate flows across multiple applications and services. Automated workflows are called flows. Once a flow is built, it’s manageable on the desktop or through an app over the mobile device. Flow can be integrated with many Microsoft services. The Microsoft Flow Admin Center allows an administrator to manage permissions, roles and users, and many more features. Visit this page to have answers to some frequent questions related to Microsoft Flow.

Though Microsoft Azure Web Job is very efficient and reliable tool for such automated functionalities, it is cost effective too as it requires the Azure subscription.

On the other hand, Microsoft Flow provides a Recurrence trigger i.e. Microsoft Recurrence Flow. It is also called Microsoft Scheduled Flow. This trigger runs event/task at regular customized time intervals. Using this, one can achieve various event/task like sending newsletter email, sending notifications/alerts etc. on recurrent bases. This flow can be scheduled on required recurrent frequency i.e. daily, weekly, hourly, monthly etc. to perform a scheduled task. As Microsoft Flow already belongs to Microsoft Office 365 platform, it does not require any additional subscription.

Let’s dive more into this to see an example of MS Recurrence flow.

Create Microsoft Recurrence Flow

Let’s assume, there is a list of Daily task in an Office 365 site collection. Each task has an expiry date and assigned user as shown below.

List of Daily Task

Flow Requirement: Create a Microsoft Recurrence Flow which will run Daily and trigger an alert email to an assigned user 3 days before the expiry date. Walkthrough below steps to create this flow.

  1. From the app launcher icon of the Office 365 portal, click Flow. This will redirect to My Flows page.

    My Flows Page

  2.  

  3. Click + New > + Create from blank.

    Create New Flow

  4.  

  5. Click on Create from blank from below the screen.

    Create a Flow from Blank

  6.  

  7. From the Triggers panel, find and select Recurrence.

    Triggers panel

  8.  

  9. Set Values for recurrence, Interval = 1 and Frequency = Day.

    Set Values for recurrence

  10.  

  11. Click on + New Step.

    Click on New Step

  12.  

  13. From the action panel, find and select Get Items action.

    Action Panel

  14.  

  15. Set values, Site Address = Your site collection URL and List Name = Name of the list.

    Set Site Address & List Name

  16.  

  17. Click on + New step > From the action panel, find and select Apply to each.

    Select "Apply to each" From Action Panel

  18.  

  19. Select the “value” variable from the Dynamic content pane and then click Add an action inside the box.

    Select the value

  20.  

  21. From the action panel, find and select action Condition.

    Select Condition from Action Panel

  22.  

  23. Set values of this condition as below:
    1. Choose a value = Expiry DateChoose a value - Expiry Date
    2. Keep is equal to in middle dropdown
    3. Add an expression to calculate the difference between today and Expiry date in the right side Choose a value box.
    4. Expression = formatDateTime (addDays (utcnow(), 3), ‘yyyy-MM-dd’)Set Expression
    5. If Expiry date = Today’s date + 3 then this condition will satisfy and an alert email will be triggered to assigned user.
  24.  

  25. Inside If yes section, find and add an action “Send an email”

    Add an action - Send an email

  26.  

  27. Set email address, subject and body as per requirement.

    Set Email Address, Subject & Body

  28.  

  29. If there is a requirement to perform some action when the condition is False, then those actions can be performed inside If no section.
  30.  

  31. As shown in the earlier screenshot of the Daily Task list, an assigned user of a task which has an expiry date as “19/11/2018” will get alert email on “16/11/2016”.

    Task Expiration

 

Conclusion

The development of recurrence task can be easily accomplished in less time and in an effective way with Microsoft Flow compared to Microsoft Azure Web Job. Thus, an organization having Microsoft Office 365 subscription can achieve many automated tasks through Microsoft Flow’s various templates.

 

 

20
Nov
2018
Use of PnP JS Core JavaScript Library

In SharePoint on-premise, to perform various basic custom operations on SharePoint lists or libraries CAML/XML-based feature is used. Later, these operations are provided using the client-side object model (CSOM), REST API, etc. In Microsoft SharePoint Online and Microsoft Office 365, various operations are served through remote provisioning technique, i.e. CSOM. Customization is provisioned in full trust code solutions or sandbox solutions.

13
Nov
2018
Custom Authentication and Authorization in WCF

Custom Authentication in WCF

Windows Communication Foundation (WCF) is a .Net framework to build and develop service applications and also enhances to support multiple different protocols than its traditional “web service” counterpart like https, IPC, MSMQ, TCP etc.

26
Oct
2018
Create Image Library using SPFx in SharePoint Online

Looking to the issue currently or normally faced by SharePoint Developers and the client’s using SharePoint Online solution regarding creating the SharePoint Picture or Image library manually – we have come up with the concept to create it programmatically. In the previous blog – we provided assistance regarding how to create SPFx web part to display the content of the Picture/Image albums from the Image Library.

24
Oct
2018
Know How Twilio APIs Works

Twilio is a powerful and well established cloud communication platform that helps you connect to your customers through Voice, SMS, Video, chat and many more channels. Reach one customer or a million on their preferred channel with Twilio API calls. We can help you to implement this and take your customer communication experience to the next level.

16
Oct
2018
Concept of Low-Code Development Environment

A Low-code development platform provides an environment for programmers. A Low-code development platform use to create application software through graphical user interfaces (GUIs) and configuration instead of traditional computer programming using various IDEs like Visual Studio, Dream Viewer, Net Beans, etc.

05
Oct
2018
SharePoint Framework Extensions – Quick Tutorial

From the time SharePoint Framework was launched, it opened new ways for SharePoint Developers to build and deploy modern web parts across Office 365 tenants. SharePoint Framework availability enabled the users to build mobile-friendly, intuitive web parts using latest web developer tools.

28
Sep
2018
Notification Extensions in iOS Apps

Apple has introduced two notification extensions through which as an iOS developer can customize local and remote push notification. These two extensions are,

  1. UNNotificationContent Extension
  2. UNNotificationService Extension