© The Author(s), under exclusive license to APress Media, LLC , part of Springer Nature 2021
J. NSBuilding Solutions with Microsoft Teamshttps://doi.org/10.1007/978-1-4842-6476-8_8

8. Extend Your Solution with Microsoft Graph

Jenkins NS1  
(1)
Chennai, India
 

In this chapter, I will be covering the automation of Teams lifecycle management, messages, webhooks, and resource-specific permission consent. Microsoft Graph is a unified API endpoint for dealing with data so that there is a graph endpoint for SharePoint, Teams, exchanges, and planning a whole variety of different Microsoft products, all exposed under a common API endpoint. Teams allows you to build a variety of different apps like tabs, bots, connectors, etc.

Overview of Graph API

Microsoft Graph is the unified REST API for accessing all the data in Microsoft’s applications, and Microsoft Teams is the hub for teamwork in Office 365 allowing you to communicate through chat messages, online meetings, and calls. It allows you to collaborate with all of those Office 365 applications.

The API enables you to access Microsoft Cloud service resources. After you register your app and get authentication tokens for a user or service, you can make requests to the Microsoft Graph API. It exposes REST APIs and client libraries to access data on the following Microsoft 365 services:
  • Office 365 services: Delve, Excel, Microsoft Bookings, Microsoft Teams, OneDrive, OneNote, Outlook/Exchange, Planner, and SharePoint;

  • Enterprise Mobility and Security services: Advanced Threat Analytics, Advanced Threat Protection, Azure Active Directory, Identity Manager, and Intune;

  • Windows 10 services: activities, devices, notifications (Figure 8-1).

../images/502225_1_En_8_Chapter/502225_1_En_8_Fig1_HTML.jpg
Figure 8-1

Microsoft Graph – One endpoint

Teams Graph APIs

Microsoft Graph provides APIs for accessing data and you can call graph APIs from tabs, bots, and websites and services that don’t have user interfaces or even Graph APIs in your command-line tools.

A Microsoft Teams Graph API allows you to create new teams and add channels to those teams, add members to the teams, and add tabs into those channels that you have created. Once the team has run its life cycle, you then have a fully functioning team. You can then archive or delete the team using the Graph API for that functionality. Also, there are different things that people build with this first Graph API; for example, they bulk provision teams – maybe 100 teams for each department at the beginning of a year.

The second thing is that you can create temporary teams. For instance, if you are an airline and you want to fly a flight each day and have a team for each flight, you can do so at the stroke of midnight. The third thing is that people create a lot of admin tools; they just administer their teams so the PowerShell command that teams have are built on this. The modern portal for admin is also built on the Graph API so that the developer can get started with the teams Graph API to manager all teams admin activities.

You have a bunch of APIs today to do that (Table 8-1), and you have access to the team resources. You can read, write, add, remove, update, delete, as well as enumerate the teams that a member has. You have APIs for manipulating membership, adding and removing people to the membership list, adding and removing people to the owner list, and also enumerating who those owners and members are; and getting additional information about them such as what their full name is, their email address, their user picture, etc.
Table 8-1

APIs Available Today for Microsoft Teams

Resource

Methods

team

List your teams, list all teams, create, read, update,

delete, clone, archive, unarchive

group

Add member, remove member, add owner, remove owner, get files, get notebook, get plans, get calendar

channel

List, create, read, update, delete

teamsTab

List, create, read, update, delete

teamsApp

List, publish, update, remove

teamsAppInstallation

List, install, upgrade, remove

chatMessage

Send

call

Answer, reject, redirect, mute, unmute, change screen sharing role, list participants, invite participants

schedule

Create or replace, get, share

schedulingGroup

Create, List, Get, Replace, Delete

shift

Create, List, Get, Replace, Delete

timeOff

Create, List, Get, Replace, Delete

timeOffReason

Create, List, Get, Replace, Delete

Team settings is another one of the things you can get access to - both reading and writing the settings of a team. With channels, we have the full ability to add, read, update, delete channels, as well as enumerate the channels in a team. And you can post channel messages to those channels.

Graph API for Lifecycle Management

One of the powerful things you can do with Graph APIs is to automate the life cycle of your team. So, you can create a team and then add members and owners to that team, add some channels to that team, configure the team settings, post a welcome message to the team, and then let your users party on that team and when they are done, when the business issue that you are trying to that team is resolved, you can then go ahead and delete the team (Figure 8-2).
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig2_HTML.jpg
Figure 8-2

Graph can automate team life cycle [REF – MSDN]

Teams and Groups

Microsoft 365 groups address the various needs of group collaboration and having 19 Microsoft 365 applications endpoints including Microsoft Teams. All Microsoft group features are applicable to Microsoft Teams. Every Team associated with a group communicates in the context of a specific team. Group members communicate by group conversations, which are email conversations that occur in the context of a group in Outlook. To differentiate the group associated with the team, any group that has a team has a ‘resourceProvisioningOptions’ property that contains “Team.” Do not change “Team” from the ‘resourceProvisioningOptions’ property or the result will be incorrect when you list all the teams.

The following are the differences at the API level between teams and groups:
  • Persistent chat is available only to Microsoft Teams. This feature is hierarchically represented by the channel and ‘chatMessage’ resources.

  • Group conversations are available only to Microsoft 365 groups. This feature is hierarchically represented by the conversation, ‘conversationThread’, and post resources.

  • The List joined teams method applies only to Microsoft Teams.

  • Calling and online meeting APIs apply only to Microsoft Teams.

You can create teams:
  • From scratch, using your own team

  • From an existing O365 group

  • By cloning an existing team

  • From a template

Here is the syntax:
POST https://graph.microsoft.com/v1.0/teams
Content-Type: application/json
{
  "[email protected]": "https://graph.microsoft.com/beta/teamsTemplates('standard')",
  "displayName": "My Sample Team",
  "description": "My Sample Team’s Description",
    "https://graph.microsoft.com/beta/users('userId')"
  ]
}

Team Templates

Spin up new teams quickly with preconfigured templates that include things like channels, owner settings, and preinstalled apps.

Out-of-the-box templates:
  • Standard

  • Education (class, staff, or PLC)

  • Retail store (basic or manager collaboration)

  • Health care (ward or hospital)

Set Up Your Team Using Graph API

You can configure your team when you create it or update it later.

Configure things like:
  • Display name and description

  • Guest and member permissions

  • Visibility

  • Messaging permissions

  • Create channels

  • Add members and roles

Here is the syntax:
PATCH https://graph.microsoft.com/v1.0/teams/{id}
Content-type: application/json
Content-length: 211
{
  "memberSettings": {
    "allowCreateUpdateChannels": true
  },
  "messagingSettings": {
    "allowUserEditMessages": true,
    "allowUserDeleteMessages": true
  },
  "funSettings": {
    "allowGiphy": true,
    "giphyContentRating": "strict"
  },
  "discoverySettings": {
    "showInTeamsSearchAndSuggestions": true
  }
}

Add Apps and Tabs Using Graph API

Preinstall apps, add tabs, and configure your tabs to install apps for your team:
  • Your app must be in either your organizational app Catalog or the public app store.

  • To add tabs for your team:
Here is the syntax:
POST https://graph.microsoft.com/v1.0/teams/{team-id}/channels/{channel-id}/tabs
{
    "displayName": "Document%20Library1",
    "[email protected]": "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/com.microsoft.teamspace.tab.files.sharepoint",
    "configuration": {
        "entityId": "",
        "contentUrl": "https://microsoft.sharepoint.com/teams/WWWtest/Shared%20Documents",
        "removeUrl": null,
        "websiteUrl": null
    }
}
POST https://graph.microsoft.com/v1.0/teams/{id}/installedApps
Content-type: application/json
{
"[email protected]":"https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/12345678-9abc-def0-123456789a"
}

Archive Your Team

When the time comes, use Graph to archive your team in an agile manner and if necessary, un-archive the team.

Common archive operations:
  • Retrieve and archive messages in important channels (beta)

  • Archive the team

  • Set the SharePoint Online team site to read only (or delete the group)

  • Archive or move stored files

Here is the syntax:
GET https://graph.microsoft.com/v1.0/teams/{id}/channels
GET https://graph.microsoft.com/beta/teams/{id}/channels/{id}/messages/delta
GET https://graph.microsoft.com/beta/teams/{id}/channels/{id}/messages/{id}/replies
POST https://graph.microsoft.com/v1.0/teams/{id}/archive
{
    "shouldSetSpoSiteReadOnlyForMembers": true
}

Graph and Bots: Better Together

A Teams app with a bot can proactively send messages to a chat or channel. It can only send messages to conversations. If it has the right information for a 1:1 chat, the bot needs to be installed in a group chat or channel the user is a part of or installed as a personal app for that user. The bot must store a reference to that user when they are made aware of them.

With Graph, you can install the app for any user, enabling proactive messaging regardless of where the app is previously installed. This is particularly useful in scenarios where you need to message a large portion of your organization reliably.

Bots can only read messages, and they are @mentioned:
  • Use messaging APIs to get additional information for your bot

  • Get the root message in a reply chain

  • Retrieve all replies to a message

  • Get previous messages from a chat thread

Microsoft Graph Toolkit

The Microsoft Graph Toolkit is a collection of reusables, framework-agnostic web components, and helpers for accessing and working with Microsoft Graph. The components are fully functional right of out of the box, with built-in providers that authenticate with and fetch data from Microsoft Graph. The Microsoft Graph Toolkit makes it easy to use Microsoft Graph in your application.
   <mgt-login></mgt-login>
   <mgt-agenda></mgt-agenda>

What’s in the Microsoft Graph Toolkit?

Components

The Microsoft Graph Toolkit includes a collection of web components for the most commonly built experiences powered by Microsoft Graph APIs.

Component

Description

Login

A button and a flyout control to authenticate a user with the Microsoft Identity platform and display the user’s profile information on sign in.

Person

Displays a person or contact by their photo, name, and/or email address.

People

Displays a group of people or contacts by their photos or initials.

Agenda

Displays events in a user or group’s calendar.

Tasks

Displays and enables adding, removing, completing, or editing of tasks from Microsoft Planner or Microsoft To-Do.

People picker

Provides the ability to search for people and renders the list of results.

Person card

A flyout used on the person component to display more profile information about a user.

Get

Make a GET query to any Microsoft Graph API directly in your HTML.

Channel picker

Provides the ability to search for Microsoft Teams channels to select a channel from a rendered list of results.

Providers

The components work best when used with a provider. Providers enable authentication and provide the implementation for acquiring the access tokens for calling the Microsoft Graph APIs.

Providers

Description

MSAL

Uses MSAL.js to sign in users and acquire tokens to use with Microsoft Graph.

SharePoint

Authenticates and provides Microsoft Graph access to components inside of SharePoint web parts.

Teams

Authenticates and provides Microsoft Graph access to components inside of Microsoft Teams tabs.

Proxy

Allows the use of back-end authentication by routing all calls to Microsoft Graph through your back end.

Custom

Creates a custom provider to enable authentication and access to Microsoft Graph with your application’s existing authentication code.

Why Use the Microsoft Graph Toolkit?

The Microsoft Graph Toolkit makes it quick and easy to integrate common experiences powered by Microsoft Graph into your own applications.

Cut Development Time

The work to connect to Microsoft Graph APIs and render the data in a UI that looks and feels like a Microsoft 365 experience is done for you, with no customization required.

Works Everywhere

All components are based on web standards and work seamlessly with any modern browser and web framework (React, Angular, Vue, etc.).

Beautiful but Flexible

The components are designed to look and feel like Microsoft 365 experiences but are also customizable using CSS custom properties and templating.

Styling Components in the Microsoft Graph Toolkit

Use CSS custom properties to modify component styles. Each component documents a set of CSS custom properties that you can use to change the look and feel of certain elements. For example:
    mgt-person {
      --avatar-size: 34px;
    }

You can’t style internal elements of a component unless you provide a CSS custom property. The component child elements are hosted in a shadow dom https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM.

Templates in the Microsoft Graph Toolkit

Use custom templates to modify the content of a component. All web components support templates based on the <template> element. For example, to override the template of a component, add a <template> element inside a component.
   <mgt-agenda>
     <template data-type="event">
          <div>{{event.subject}}</div>
         <div data-for='attendee in event.attendees'>
              <mgt-person person-query="{{attendee.emailAddress.name}}">
               <template>
                 <div data-if="person.image">
                   <img src="{{person.image}}" />
                  </div>
                 <div data-else>
                    {{person.displayName}}
                 </div>
                </template>
              </mgt-person>
          </div>
      </template>
   </mgt-agenda>

Data Type

Each component can have multiple parts that can be templated.

For example, in the mgt-agenda component, you can template individual events, individual section headers, loading view, no data view, and more. To indicate the template, use the data-type attribute on a template.
   <mgt-agenda>
     <template data-type="event"> </template>
   </mgt-agenda>

If no data type is specified, the entire component will be replaced with the template. You can also use data type="default" for the same purpose.

Binding Data

Many templates allow binding of data that is passed to the template as data context. For example, the event template in the mgt-agenda component passes an {event} object that can be used directly in the template. To expand an expression, such as event, the subject uses the double curly brackets.
<template data-type="event">
  <div>{{event.subject}}</div>
</template>
This format can also be used inside attributes:
<template data-type="event">
  <a href="{{ event.onlineMeetingUrl }}" />
</template>

Change Binding Syntax

By default, to expand an expression, you use double curly brackets ( {{expression}} ). However, you can change this syntax for environments where the double curly bracket syntax is already used. For example, the following example uses double square brackets ( [[expression]] ).
import { TemplateHelper } from '@microsoft/mgt';
TemplateHelper.setBindingSyntax('[[', ']]');

Data Context Helper Properties

The following properties can also be used with the data context object in your templates.

Property

Description

$index

Numerical index of item being rendered while being looped with data-for.

$parent

If a template is rendered inside another template, this property allows you to access the parent data context.

The following example shows how to use the $index property in a data-for loop.
<mgt-person>
  <mgt-person-card>
    <template data-type="additional-details">
      <span data-for="language in languages">
        {{ language.displayName }}<span data-if="$index < languages.length - 1">, </span>
      </span>
    </template>
  </mgt-person-card>
</mgt-person>

Conditional Rendering

You might only want to render elements when a condition is true or false based on the data context. The data-if and data-else attributes can evaluate an expression and render only if they are true or false.
<mgt-person person-query="john doe">
  <template>
    <div data-if="person.image">
      <img src="{{ person.image }}" />
    </div>
    <div data-else>
      {{ person.displayName }}
    </div>
  </template>
</mgt-person>

Looping

There will be cases where the data context object contains a loop and you will need to loop over the data. For this scenario, use the data-for attribute.
<template data-type="event">
  <ul>
    <li data-for='attendee in event.attendees'>
      {{ attendee.displayName }}
    </li>
  </ul>
</template>

Template Context

In scenarios where you need to convert data in your bindings, bind to events, or just use external data in your template’s bindings, the templates support binding to external data context. You can add additional template context in two ways.

Directly on the Component
Each component defines the templateContext property, which you can use to pass additional data to any template in the component.
   document.querySelector('mgt-agenda').templateContext = {
     someObject: {},
      formatDate: (date: Date) => { /* format date and return */ },
     someEventHandler: (e) => { /* handleEvent */  }
   }

The properties in the templateContext object will now be available to be used in the binding expressions in the template.

Globally for All Components
The TemplateHelper class exposes the globalContext object to add data or functions that should be globally available for all components.
   import { TemplateHelper } from '@microsoft/mgt';
   TemplateHelper.globalContext.someObject = {};
   TemplateHelper.globalContext.formatDate = (date: Date) => { /* format date and return */ };
   TemplateHelper.globalContext.someEventHandler = (e) => { /* handleEvent */  }

Converters

In many cases, you might want to transform the data before presenting it in the template. For example, you might want to properly format a date before it is rendered. In these cases, you might want to use a template converter.

To use a template converter, you first need to define a function that will do the conversion. For example, you might define a function to convert an event object to a formatted time range.
    document.querySelector('mgt-agenda').templateContext = {
     getTimeRange: (event) => {
       // TODO: format a string from the event object as you wish
       // timeRange = ...
        return timeRange;
     }
  }
To use the converter in your template, use it as if you would use a function in the code behind.
    <template data-type="event">
      <div>{{ getTimeRange(event) }}</div>
    </template>

Event or Property Binding

The data-props attribute allows you to add an event listener or set a property value directly in your templates.
   <template>
        <button data-props="{{@click: myEvent, myProp: value}}"></button>
   </template>
The data-props accepts a comma delimited string for each property or event handler you might want to set. To add an event handler, prefix the name of the event with @. The event handler will need to be available in the templateContext of the element.
   document.querySelector('mgt-agenda').templateContext = {
      someEventHandler: (e, context, root) => { /* handleEvent */  }
   }
   <template>
        <button data-props="{{@click: someEventHandler}}"></button>
    </template>

The event args, data context, and root element of the template are passed to the event handler as parameters.

Template Rendered Event

In certain cases, you might want to get a reference to the rendered element. This can be useful if you want to handle the rendering of the content yourself, or you want to modify the rendered element.

In this scenario, you can use the templateRendered event, which fires after the template has been rendered.
let agenda = document.querySelector('mgt-agenda');
agenda.addEventListener('templateRendered', (e) => { });
The event details will contain a reference to the element that is being rendered, data context object, and type of template.
agenda.addEventListener('templateRendered', (e) => {
  let templateType = e.detail.templateType;
  let dataContext = e.detail.context;
  let element = e.detail.element;
  if (templateType === 'event') {
    element.querySelector('.some-button').addEventListener('click', () => {});
  }
});

Microsoft Graph Toolkit Playground

To find a tool used for interacting with the Microsoft Graph Toolkit, try out the components in this playground: https://mgt.dev . See Figure 8-3.
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig3_HTML.jpg
Figure 8-3

Graph Toolkit playground

Microsoft Graph Explorer

Microsoft Graph Explorer is a tool to explore graph APIs, and you can see the image in Figure 8-4 of the screenshot of the Microsoft Graph Explorer that I have captured. As you can see, this console gives you the option to type in the API or address of a specific entity type or object for which you are looking for some information, and then you also need to sign in with a specific account that has the privilege to query this particular API, Next it will also show you some of the sample queries that you can use to understand the explorer. You can access Graph Explorer at: https://developer.microsoft.com/graph/graph-explorer

The following example shows a request that returns information about joinedteams in my tenant.
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig4_HTML.jpg
Figure 8-4

Graph API Explorer

A status code and message are displayed after a request is sent and the response is shown in the Response Preview tab.

Postman

Postman is a collaboration platform for API development that you can use to build and test Microsoft Graph API requests. You can download Postman from https://www.getpostman.com . To interact with Microsoft Graph in Postman, you use the Microsoft Graph collection. To learn more about postman, refer here: https://learning.postman.com/

Microsoft Teams Toolkit for Visual Studio Code

The Microsoft Teams Toolkit extension enables you to create, debug, and deploy Teams apps directly from Visual Studio Code.

Prerequisites:
  • Visual Studio Code v1.44 or newer

  • NodeJS 6 or newer

To access the Microsoft Teams Toolkit: - https://marketplace.visualstudio.com/items?itemName=TeamsDevApp.ms-teams-vscode-extension . See Figure 8-5.
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig5_HTML.jpg
Figure 8-5

Microsoft Teams Toolkit

Exercise – Microsoft Teams Tabs Using Microsoft Graph Toolkit

In this exercise, you will learn the basics of Microsoft Graph in Microsoft Teams and how to use Microsoft Graph API Toolkit, Microsoft Graph Explorer, and AAD Permission Implementation. This exercise develops using Microsoft Teams Toolkit for Visual Studio Code.

Before starting the exercise, verify your environment. In this exercise, I am using the tools mentioned below, which are installed in my environment:
  1. 1.

    Visual Studio Code

     
  2. 2.

    Microsoft Teams Toolkit

     
  3. 3.

    Ngrok account

     
Steps to build a Teams tab using Microsoft Graph API Toolkit:
  1. 1.

    Install Microsoft Teams Toolkit extension for Visual Studio Code

     
  2. 2.
    Build Microsoft Teams tab
    • Implement Microsoft Graph Toolkit
      • Login component: login button to authenticate a user with the Microsoft Identity platform

      • Teams provider: Microsoft Teams tab to facilitate authentication

      • Person component: displays user

     
  3. 3.

    Set up ngrok for tunneling

     
  4. 4.

    Register your app in Azure Active Directory

     
  5. 5.

    Execute the app

     
  6. 6.

    Test your App in Microsoft Teams

     

Enable Microsoft Teams Toolkit Extension for Visual Studio Code

Install Microsoft Teams Toolkit from the Extensions tab on the left sidebar in Visual Studio Code. See Figure 8-6.
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig6_HTML.jpg
Figure 8-6

Microsoft Teams Toolkit Installation

Build Microsoft Teams Tab

Here are the steps (Figure 8-7):
  1. 1.

    Open Visual Studio Code

     
  2. 2.

    Select Microsoft Teams icon on the left sidebar in Visual Studio Code and Sign in

     
  3. 3.

    Log in with your tenant account

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig7_HTML.jpg
Figure 8-7

Microsoft Teams Toolkit Sign In

  1. 4.

    Navigate to “Create a New Teams app” and Click to enter new app name (Figure 8-8)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig8_HTML.jpg
Figure 8-8

Create new App

  1. 5.

    Press ‘Enter’ to select the app path

     
  2. 6.

    Choose Tab to create Microsoft Teams Tab (Figure 8-9)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig9_HTML.jpg
Figure 8-9

Select new tab App

  1. 7.

    Click Next button

     
  2. 8.

    Select Personal tab (Figure 8-10)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig10_HTML.jpg
Figure 8-10

Select Personal App

  1. 9.

    Click the Finish button to create the Teams app (Figure 8-11)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig11_HTML.jpg
Figure 8-11

Microsoft Teams Tab App Created

Implement Microsoft Graph Toolkit

Let’s implement it:
  • Add a new file under src folder and name it as auth.js

  • Then add the code below in it:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import { Provider, themes } from '@fluentui/react-northstar'
ReactDOM.render(
    <Provider theme={themes.teams}>
        <App />
    </Provider>, document.getElementById('auth')
);
  • Add a new file under public folder and name as auth.html

  • Then add below code

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Auth Tab</title>
    <meta name="viewport" content='width=device-width, initial-scale=1'>
    <link rel="stylesheet" type='text/css' media="screen" href='main.css'>
    <script src='main.js'></script>
</head>
<body>
    <div id="auth"></div>
    <script src="https://unpkg.com/@microsoft/teams-js/dist/MicrosoftTeams.min.js" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
    <script>
        mgt.TeamsProvider.handleAuth();
    </script>
</body>
</html>
  • Add the code below in index.html, inside <body> tag:

<div id="root"></div>
    <script src="https://unpkg.com/@microsoft/teams-js/dist/MicrosoftTeams.min.js" crossorigin="anonymous"></script>
    <script src="https://unpkg.com/@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
    <mgt-teams-provider client-id=" YOUR-CLIENT-ID" auth-popup-url="YOUR-NGROK-URL/auth.html"></mgt-teams-provider>
    <mgt-login></mgt-login>
    <mgt-person id="with-presence" person-query="me" person-card="hover" view="twoLines" show-presence></mgt-person>

Set Up Ngrok for Tunneling

Follow these steps:
  • Go to the ngrok(https://ngrok.com/) website and log in with your tenant id

  • Download ngrok.exe and Complete the setup and installation guide

  • Copy the Authtoken from the ngrok site

  • Save Authtoken in the default configuration file C:Users[user name].ngrok> (Figure 8-12)

../images/502225_1_En_8_Chapter/502225_1_En_8_Fig12_HTML.jpg
Figure 8-12

configUre ngrok auth token

  • Run the script below (Figure 8-13) to create an ngrok tunnel for https://localhost:3000

../images/502225_1_En_8_Chapter/502225_1_En_8_Fig13_HTML.jpg
Figure 8-13

Ngrok created the tunnel

ngrok http -host-header="localhost:3000" 3000
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig14_HTML.jpg
Figure 8-14

Update URL in .env file

../images/502225_1_En_8_Chapter/502225_1_En_8_Fig15_HTML.jpg
Figure 8-15

Update URL in index file

  • Navigate Terminal ➤ New Terminal

  • Run the solution (Figure 8-16). Default Teams tab will be running https://localhost:3000

npm install
npm start
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig16_HTML.jpg
Figure 8-16

Compiled the app

Register Your App in Azure Active Directory

Now we register the app:
  1. 1.

    Go to the Azure Portal, then Azure Active Directory ➤ App Registration and select New Registration

     
  2. 2.

    Azure Active Portal URL - https://aad.portal.azure.com/

     
  3. 3.

    Login

     
  4. 4.

    Click Azure Active Directory

     
  5. 5.

    Select App registrations

     
  6. 6.

    Then Click New Registration (Figure 8-17)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig17_HTML.jpg
Figure 8-17

App registrations

  1. 7.
    Fill in the Details for registering an app:
    • Name: TeamsTabApp

    • Supported Account type : Accounts in any organizational directory (Any Azure AD directory - Multitenant) and personal Microsoft accounts (e.g., Skype, Xbox)

    • Redirect URL for web: https://REPLACE_NGROKDOMAIN.ngrok.io/auth.html

    • Click ‘Register’ button to register an application (Figure 8-18)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig18_HTML.jpg
Figure 8-18

Register an application

  1. 8.

    Go to the Authentication tab and Enable Implicit grant by selecting Access tokens and ID tokens (Figure 8-19)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig19_HTML.jpg
Figure 8-19

Authentication

  1. 9.

    Click Save

     
  2. 10.
    Go to API permissions tab (Figure 8-20), select Add a permission ➤ Microsoft Graph ➤ Delegated permissions and add permission
    1. a.

      Calendar.Read

       
    2. b.

      Calendar.ReadWrite

       
    3. c.

      Directory.AccessAsUser.All

       
    4. d.

      Directory.Read.All

       
    5. e.

      Directory.ReadWrite.All

       
    6. f.

      User.Read

       
    7. g.

      User.Read.All

       
    8. h.

      User.ReadWrite.All

       
    9. i.

      Mail.Read

       
     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig20_HTML.jpg
Figure 8-20

Request API permission

  1. 11.

    Then, select Grant admin consent (Figure 8-21)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig21_HTML.jpg
Figure 8-21

Grant Admin consent

  1. 12.

    Go to Overview tab and copy Application (client) ID (Figure 8-22)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig22_HTML.jpg
Figure 8-22

Application client ID

  1. 13.

    Then go to your project public > index.html, and replace YOUR-CLIENT-ID with Application (client) ID in mgt-teams-provider > auth-popup-url (Figure 8-23).

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig23_HTML.jpg
Figure 8-23

update client ID in index file

Test Your App in Microsoft Teams

It is time to test it:
  1. 1.

    Go to Microsoft Teams (https://teams.microsoft.com )

     
  2. 2.

    Go to … ➤ open App Studio (Figure 8-24)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig24_HTML.jpg
Figure 8-24

Open App Studio

  1. 3.

    Select Manifest Editor and select Import an existing app (Figure 8-25)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig25_HTML.jpg
Figure 8-25

Import an existing app

  1. 4.

    Select Development.zip under your project folder ➤ .publish (Figure 8-26)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig26_HTML.jpg
Figure 8-26

Import Development.zip file

  1. 5.

    Scroll down and select Test and distribute, then click Install (Figure 8-27)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig27_HTML.jpg
Figure 8-27

Install the app for testing

  1. 6.

    Click the Add button to install the app (Figure 8-28)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig28_HTML.jpg
Figure 8-28

Add the app for testing

  1. 7.

    Click Sign in for the authentication using an AAD registered app (Figure 8-29)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig29_HTML.jpg
Figure 8-29

Sign in the app

  1. 8.

    Give consent to the AAD registered app you created (Figure 8-30)

     
../images/502225_1_En_8_Chapter/502225_1_En_8_Fig30_HTML.jpg
Figure 8-30

Give consent to AAD

../images/502225_1_En_8_Chapter/502225_1_En_8_Fig31_HTML.jpg
Figure 8-31

Get User info using Graph API toolkit

  1. 9.

    Your profile information email and name should appear in your tab after the successful authentication (Figure 8-31)

     

In this exercise, you have learned how to use Microsoft Teams Toolkit for Visual Studio code with Microsoft Graph API toolkit within Microsoft Teams for a tab app.

Conclusion

In this chapter, you have learned various features of Microsoft Teams Toolkit, Microsoft Graph API Toolkit, and Graph API with examples that we can be able to use from our own custom application. Along with this you will start learning different options and features of Microsoft Teams apps in our upcoming chapters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.66.178