Authentication in Teams tabs using Microsoft Graph Toolkit

If you are looking for ways to build easy authentication for Microsoft Teams custom tab developmentMicrosoft Graph Toolkit Login component provides a button and flyout control to facilitate Microsoft identity platform authentication with couple of lines of code.

How to build a tab with straightforward authentication flow?

  1. Enable Microsoft Teams Toolkit extension for Visual Studio Code
  2. Build Microsoft Teams tab
  3. Implement Microsoft Graph Toolkit:
  4. Setup ngrok for tunneling
  5. Register your app in Azure Active Directory
  6. Import your app manifest to Microsoft Teams App Studio for testing

Enable Microsoft Teams Toolkit extension for Visual Studio Code

Install Microsoft Teams Toolkit from the Extensions tab on the left side bar in Visual Studio Code. For more information, Microsoft Teams Toolkit: Setup and Overview.

Microsoft Teams Toolkit Extension for Visual Studio Code

Build Microsoft Teams tab

  • Select Microsoft Teams icon on the left side bar in Visual Studio Code and Sign in.
Microsoft Teams Toolkit Extension for Visual Studio Code
  • Select Create a new Teams app,
    • Give a name for the app
    • Choose Tab for the capability
    • Select Next
Microsoft Teams Toolkit Extension for Visual Studio Code
  • Select Personal tab
  • Select Finish
Microsoft Teams Toolkit Extension for Visual Studio Code
  • Open Terminal and run:
    npm install
    npm start

Implement Microsoft Graph Toolkit

Add a new file under src folder and name it as Auth.js.

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './components/App';
import { Provider, themes } from '@fluentui/react-northstar' //https://fluentsite.z22.web.core.windows.net/quick-start

ReactDOM.render(
    <Provider theme={themes.teams}>
        <App />
    </Provider>, document.getElementById('auth')
);

Add a new file under public folder and name as auth.htmlCTRL+SPACE for adding HTML Sample. Add below code in <body></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>

Add below code in index.html <body></body>

 <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-agenda></mgt-agenda>

Setup ngrok for tunneling

npm start

  • Go to ngrok website and login.
  • Complete the setup and installation guide.
  • Save Authtoken in the default configuration file C:\Users\[user name]\.ngrok:

ngrok authtoken <YOUR_AUTHTOKEN>

ngrok http https://localhost:3000

Ngrok Setup
Ngrok Setup
Ngrok Setup
  • Go to your project public > index.html, replace YOUR-NGROK-URL with ngrok url https://xxxxxxxxxxxx.ngrok.io in mgt-teams-provider > auth-popup-url.
Ngrok Setup

Register your app in Azure Active Directory

  • Go to Azure Portal, then Azure Active Directory > App Registration and select New Registration.
Ngrok Setup
  • Fill the details to register an app:
    • give a name to your application
    • select Accounts in any organizational directory as an access level
    • place auth-popup-url as the redirect url https://xxxxxxxxxxxx.ngrok.io/auth.html
    • select Register
Ngrok Setup
  • Go to Authentication tab and enable Implicit grant by selecting Access tokens and ID tokens
Ngrok Setup
  • Go to API permissions tab, select Add a permission > Microsoft Graph > Delegated permissions and add Calendar.ReadCalendar.ReadWrite.
  • Then, select Grant admin consent.
Ngrok Setup
  • Go to Overview tab and copy Application (client) ID
  • Then go to your project public > index.html, replace YOUR-CLIENT-ID with Application (client) ID in mgt-teams-provider > auth-popup-url.
Ngrok Setup
Ngrok Setup

Import your app manifest to Microsoft Teams App Studio for testing

  • Go to Microsoft Teams, open App Studio > Manifest Editor and select Import an existing app.
Ngrok Setup
  • Select Development.zip under your project folder > .publish.
Ngrok Setup
  • Scroll down and select Test and distribute, then click Install and Add your app.
Ngrok Setup
Ngrok Setup
  • Click on Sign in for the authentication and give consent to AAD registered app you created.
Ngrok Setup
  • Your profile information e-mailname and calendar should appear in your tab after the successful authentication.
Ngrok Setup
Solution repository is available here: https://github.com/aycabas/TeamsApp

Microsoft Graph Toolkit: where to get started?

If you are a starter and willing to learn more about Microsoft Graph Toolkit, you are in the right place! Before we jump into a long run project, we will discover Microsoft Graph Toolkit and find answers to the following questions:

  • What is Microsoft Graph Toolkit?
  • What is in Microsoft Graph Toolkit?
  • Where to get started?

Today, our focus will be understanding the basics. But, If you are interested in building an overall solution, check out this post: Microsoft Graph Toolkit: gather together your Office 365 in one app.

What is Microsoft Graph Toolkit?

It is a powerful collection of reusable web components and providers that enables accessing Microsoft 365 data. It makes Microsoft Graph easy to use in your application. For instance, we can implement login and tasks with just two lines of code by using Login and Tasks components.

Microsoft Graph Toolkit Playground: mgt.dev

The Microsoft Graph Toolkit is great for developers of all experience levels. All components work fluently with all modern browsers and web frameworks (React, Angular, Vue, etc.).

What is in Microsoft Graph Toolkit?

Components: a collection of web components powered by Microsoft Graph APIs

Note: The components work best when used with a provider.

ComponentHTML
Login<mgt-login></mgt-login>
Person<mgt-person person-query=”me” view=”twoLines”></mgt-person>
People<mgt-people show-max=”5″></mgt-people>
Agenda<mgt-agenda></mgt-agenda>
Tasks<mgt-tasks></mgt-tasks>
People picker<mgt-people-picker></mgt-people-picker>
Person card<mgt-person person-query=”me” view=”twoLines” person-card=”hover”></mgt-person>
  <div class=”note”>
    (Hover on person to view Person Card)
  </div>
Get<mgt-get resource=”/me/messages” version=”beta” scopes=”mail.read” max-pages=”2″>
    <template>….</template>
 </mgt-get>
Channel picker<mgt-teams-channel-picker></mgt-teams-channel-picker>
Providers: enable authentication and provide the implementation to get the access tokens for consuming Microsoft Graph APIs
ProvidersHTML
MsalSign in users and acquire tokens to use with Microsoft Graph.
SharePointAuthenticates and provides Microsoft Graph access to components inside of SharePoint web parts.
TeamsAuthenticates and provides Microsoft Graph access to components inside of Microsoft Teams tabs.
ProxyAllows the use of backend authentication by routing all calls to Microsoft Graph through your backend.
CustomCreate a custom provider to enable authentication and access to Microsoft Graph with your application’s existing authentication code.

Where to get started?

1. The Playground

Microsoft Graph Toolkit Playground is definitely a great tool for starters who wants to try out components and learn more about the capabilities of each component. It is quite helpful for discovering the components edge to edge before trying them out in a custom application. Highlights of the Playground:

  • Canvas is the place for testing the components, checking the visual results and customizing UI as our wishes.
  • Docs is the place where we can check the attributes, properties, events, css and stories for each component.
  • Finally, don’t forget to check Samples in the Playground, there are many templates available and ready to use!
2. Repository

Microsoft Graph Toolkit provides a rich repository with Angular, ASP.NET Core, React and many more other samples available. If you are looking for some sample solutions, Microsoft Graph Toolkit Repository is the great place to start exploring.

3. Docs

Here is the official documentation of the Microsoft Graph Toolkit.

Let me know about your experience with Microsoft Graph Toolkit. Furthermore, If you would like to build a solution from scratch with the power of Microsoft Graph Toolkit, check out this post: Microsoft Graph Toolkit: gather together your Office 365 in one app.

Cheers!

Microsoft Graph Toolkit: gather together your Office 365 in one app

Hey there! Today, we will work on an ASP.NET Core MVC web app with the power of Microsoft Graph Toolkit. Our purpose is to enable:

  • Microsoft identity platform authentication
  • the agenda from Outlook Calendar
  • the tasks from Planner
  • e-mails from Outlook

If you never heard of Microsoft Graph Toolkit before, it is a powerful collection of reusable web components that enables accessing Microsoft 365 data with just couple lines of code! Believe it or not, Microsoft identity platform authentication can be implemented in seconds.

This web app will be a quick scenario to try out Microsoft Graph Toolkit!

You can get the source code from here .


Create ASP.NET Core MVC web app in Visual Studio Code

  • Open the Terminal in Visual Studio Code (Ctrl+Shift+`)
  • Then, create a new folder for the project
PS C:\Users\user> cd Desktop
PS C:\Users\user\Desktop> mkdir GraphToolkitNetCore
  • Create ASP.NET Core MVC app
PS C:\Users\user\Desktop> dotnet new mvc
PS C:\Users\user\Desktop> cd GraphToolkitNetCore
  • The app is created successfully! Now, click on “Open Folder” to open your project folder.
  • Press F5 to run the project
  • Our project is working fine. Before we start building our app with Microsoft Graph Toolkit, let’s go to Properties > launchSettings.json and set http://localhost:8080to applicationUrl

Register an app in Azure Active Directory

  • First thing first, go to Azure Portal
  • Under Azure Active Directory, go to App Registration and click on New Registration
  • Give a name to your app
  • Choose the access level
  • Choose Web and place http://localhost:8080 as a Redirect URI
  • Go to Authentication tab
  • Then, check Access tokens and ID tokens
  • Finally, go to Overview tab
  • Copy Application (client) ID to a notepad, we will need it later

Setup Index.cshtml

  • Go to Index.cshtml and add a row and three columns inside the row
<div class="row" id="content">
    
    <div class="column" id="one"></div>
    <div class="column" id="two"></div>
    <div class="column" id="three"></div>
    
</div>
  • Copy below additional css to site.css under wwwroot>site.scs
/* Main content */
#content, html, body {
  height: 98%;
}
#one {
  float: left;
  width: 33%;
  background:transparent;
  height:500px;
  overflow: hidden;
}
#one:hover {
  overflow-y: auto;
}
#two {
  float: middle;
  width: 33%;
  background: transparent;
  height: 500px;
  overflow: hidden;
}
#two:hover {
  overflow-y: auto;
}
#three {
  float: left;
  width: 33%;
  background: transparent;
  height: 500px;
  overflow: hidden;
}
#three:hover {
  overflow-y: auto;
}
/*Email*/
.email {
  box-shadow: 0 3px 7px rgba(0, 0, 0, 0.3);
  padding: 10px;
  margin: 8px 4px;
  font-family: Segoe UI, Frutiger, Frutiger Linotype, Dejavu Sans, Helvetica Neue, Arial, sans-serif;
}
.email:hover {
  box-shadow: 0 3px 14px rgba(0, 0, 0, 0.3);
  padding: 10px;
  margin: 8px 4px;
}
.email h3 {
  font-size: 12px;
  margin-top: 4px;
}
.email h4 {
  font-size: 10px;
  margin-top: 0px;
  margin-bottom: 0px;
}
.email mgt-person {
  --font-size: 10px;
  --avatar-size-s: 12px;
}
.email .preview {
  font-size: 13px;
  text-overflow: ellipsis;
  word-wrap: break-word;
  overflow: hidden;
  max-height: 2.8em;
  line-height: 1.4em;
}
a.navbar-brand {
  white-space: normal;
  text-align: center;
  word-break: break-all;
}

Let’s start working with Microsoft Graph Toolkit

Login

  • Go to Home>Index.cshtml
  • Implement MSAL provider in Index.cshtml
  • Make sure it is placed under the welcome message
<script src="https://unpkg.com/@@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
<mgt-msal-provider client-id="[Client-id]"></mgt-msal-provider>
<mgt-login></mgt-login>
  • Paste Application (client) ID that you copied earlier from Azure Active Directory
  • Press F5 to run your application
  • Click on sign in button and login with your account
  • Accept to permission request
  • When the authentication is completed, you should see your details in the page

Get E-mails

  • Use mgt-get to get user’s e-mails. Implement below code as column 1 in Index.cshtml
       
<mgt-get resource="/me/messages" version="beta" scopes="mail.read" max-pages="1">
     <template>
        <div class="email" data-for="email in value">
            <h4><mgt-person person-query="{{email.sender.emailAddress.address}}" show-name person-card="hover"></mgt-person></h4>
             <h3>{{ email.subject }}</h3>
             <div data-if="email.bodyPreview" class="preview" innerHtml>{{email.bodyPreview}}</div>
             <div data-else class="preview">email body is empty</div>
        </div>
      </template>
      <template data-type="loading">loading</template>
      <template data-type="error">{{ this }} </template>
</mgt-get>  
  • Press F5 to run the app, you should be able to see the emails

Agenda

  • Use mgt-agenda to get a user or group calendar. Implement below code as column 2 in Index.cshtml
<mgt-agenda group-by-day></mgt-agenda>
  • Then, press F5 to run the app. You should be able to see the agenda on the right side of the e-mails

Tasks

  • Use mgt-tasks to get a user or group calendar. Implement below code as column 3 in Index.cshtml
<mgt-tasks></mgt-tasks>
  • Press F5 to run the app, you should be able to see the tasks on the right side of the agenda

Final version of Index.cshtml will look like below:

@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <script src="https://unpkg.com/@@microsoft/mgt/dist/bundle/mgt-loader.js"></script>
    <mgt-msal-provider client-id="[Client-id]"></mgt-msal-provider>
    <mgt-login></mgt-login>
</div>
<div class="row" id="content">
     
    <div class="column" id="one">  
        <mgt-get resource="/me/messages" version="beta" scopes="mail.read" max-pages="1">
            <template>
                <div class="email" data-for="email in value">
                    <h4><mgt-person person-query="{{email.sender.emailAddress.address}}" show-name person-card="hover"></mgt-person></h4>
                        <h3>{{ email.subject }}</h3>
                        <div data-if="email.bodyPreview" class="preview" innerHtml>{{email.bodyPreview}}</div>
                        <div data-else class="preview">email body is empty</div>
                </div>
            </template>
            <template data-type="loading">loading</template>
            <template data-type="error">{{ this }} </template>
        </mgt-get>   
    </div>
    <div class="column" id="two">
        <mgt-agenda group-by-day></mgt-agenda>
    </div>
    <div class="column" id="three">
        <mgt-tasks></mgt-tasks>
    </div>
     
</div>

Our app is ready! As a result, we have our e-mails, agenda and tasks in one place. I hope you enjoyed using Microsoft Graph Toolkit. You can get the source code from here.

Let me know about your experience or if you have any feedback!

If you are interested in learning more about Microsoft Graph, check out the related posts.