0% found this document useful (0 votes)
326 views310 pages

Building Microsoft Teams Integration and Workflows

Uploaded by

Rafa Moscote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
326 views310 pages

Building Microsoft Teams Integration and Workflows

Uploaded by

Rafa Moscote
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 310

© Copyright Microsoft Corporation. All rights reserved.

FOR USE ONLY AS PART OF MICROSOFT VIRTUAL TRAINING DAYS PROGRAM. THESE MATERIALS ARE NOT AUTHORIZED
FOR DISTRIBUTION, REPRODUCTION OR OTHER USE BY NON-MICROSOFT PARTIES.
Microsoft 365 Virtual
Training Day:
Building Microsoft Teams
Integration and Workflows
Implement Microsoft identity –
Segment 1 of 2
Getting
started with • Overview of Microsoft identity platform
Microsoft • Token types in Microsoft Identity
Identity • Register an application
Overview of Microsoft identity platform
Why use an identity provider?

Delegating authentication and authorization enables scenarios such as:


Conditional Access policies that require a user to be in a specific location
The use of multi-factor authentication
Single sign-on (SSO)

Azure Active Directory (Azure AD):


A centralized identity provider in the cloud

Microsoft identity platform:


Identity-as-a service, with support for industry-standard protocols
such as OAuth 2.0 and OpenID Connect + open-source libraries
Overview of Microsoft identity platform

Microsoft identity platform (v. 2.0) is an evolution of the Azure Active


Directory v1.0 (Azure AD) developer platform

The Microsoft identity platform consists of:


OAuth 2.0 and OpenID Connect standard-compliant authentication service
Open-source libraries
Application management portal
Application configuration API and PowerShell
Developer content
Identity

Resources Policies
Overview of Microsoft identity

Users:
Azure AD – Employees and Enterprise Resources
Azure AD B2B – Partners
Azure AD B2C – Customers/citizens

Resources:
Microsoft Graph is the gateway to your data in the Microsoft cloud

Policies:
Efficiently handle complex policies that control access to resources from different
networks and devices
External collaboration using B2B
Contoso Fabrikam
Azure Active Directory B2C

Any SAML
Social IDs provider
Microsoft Azure
Analytics
Active Directory

Business & Apps


contoso
Government IDs

Securely authenticate your customers using their preferred identity provider

Capture login, preference, and conversion data for customers

Provide branded (white-label) registration and login experiences


Gateway to your data in the Microsoft cloud

Your app

Gateway Microsoft
1 Graph

Office 365 Windows 10 Enterprise Mobility + Security


Your or your
customer’s
data
Azure AD
ADFS Conditions Controls
MSA
40TB
Google ID
Allow/block
Employee & Partner
access
Android Users and Roles Session
Risk Microsoft
iOS Machine Cloud App
learning 3 Limited Security
MacOS Trusted &
Compliant Devices access
Windows
Windows
Defender ATP
Require
Real time MFA
Evaluation
Geo-location Engine

Physical & Force


Corporate
Network Virtual Location password
******
Policies Effective
reset
Client apps & policy
Browser apps
Auth Method
Block legacy
Client apps authentication
Supported account types and topologies
Microsoft identity platform can sign in users with:
Work or school accounts (Azure AD)
Personal accounts (Microsoft accounts, such as Skype, Xbox, Outlook.com)
Social or local accounts

Single-tenant applications only sign in users from home tenant

Multi-tenant apps sign in users from multiple organizations:


In any Azure AD directory
In any Azure AD directory + personal Microsoft accounts

Azure Active Directory B2C (Azure AD B2C)

Microsoft identity platform supports the following identity topologies:


Consumer
Enterprises
Business to Business (B2B)
Business to Customer (B2C)
Token types in Microsoft identity
OpenID Connect & ID tokens

Open ID Connect extends OAuth 2.0


Uses OAuth 2.0’s authorization protocol as an authentication protocol

Enables developers to implement single sign-on using OAuth

ID token
Security token that clients can use to verify identity of user

Contains basic profile information about the user

Claims in ID tokens can be used for the user experience, keys in DB’s & providing access to
client applications
External collaboration using B2B
Contoso Fabrikam
Azure Active Directory B2C

Any SAML
Social IDs provider
Microsoft Azure
Analytics
Active Directory

Business & Apps


contoso
Government IDs

Securely authenticate your customers using their preferred identity provider

Capture login, preference, and conversion data for customers

Provide branded (white-label) registration and login experiences


Gateway to your data in the Microsoft cloud

Your app

Gateway Microsoft
1 Graph

Office 365 Windows 10 Enterprise Mobility + Security


Your or your
customer’s
data
Azure AD
ADFS Conditions Controls
MSA
40TB
Google ID
Allow/block
Employee & Partner
access
Android Users and Roles Session
Risk Microsoft
iOS Machine Cloud App
learning 3 Limited Security
MacOS Trusted &
Compliant Devices access
Windows
Windows
Defender ATP
Require
Real time MFA
Evaluation
Geo-location Engine

Physical & Force


Corporate
Network Virtual Location password
******
Policies Effective
reset
Client apps & policy
Browser apps
Auth Method
Block legacy
Client apps authentication
Supported account types and topologies
Microsoft identity platform can sign in users with:
Work or school accounts (Azure AD)
Personal accounts (Microsoft accounts, such as Skype, Xbox, Outlook.com)
Social or local accounts

Single-tenant applications only sign in users from home tenant

Multi-tenant apps sign in users from multiple organizations:


In any Azure AD directory
In any Azure AD directory + personal Microsoft accounts

Azure Active Directory B2C (Azure AD B2C)

Microsoft identity platform supports the following identity topologies:


Consumer
Enterprises
Business to Business (B2B)
Business to Customer (B2C)
Token types in Microsoft identity
OpenID Connect & ID tokens

Open ID Connect extends OAuth 2.0


Uses OAuth 2.0’s authorization protocol as an authentication protocol

Enables developers to implement single sign-on using OAuth

ID token
Security token that clients can use to verify identity of user

Contains basic profile information about the user

Claims in ID tokens can be used for the user experience, keys in DB’s & providing access to
client applications
Difference between user and application access tokens

Applications can receive tokens…

… on behalf of a user
… directly from an application (for example: daemon or service applications

App-only tokens indicate the request is coming from an application and has no user backing it
Register an application
Register an application

Registration fields:
Application name
Supported account types
Redirect URI (optional)

The application manifest:


App registrations > Manifest
Overview of application model

Application object:
The application properties stored in the
manifest
Defines the required application
permissions

Service principal object:


A copy of the application object used in
non-home tenants to define application
permissions
• Single-page applications
Implement
• Web apps that sign in users and call APIs
authentication
• Daemon and non-interactive apps
Single-page applications
Single Page Applications

Modern web applications can be built entirely client-side with JavaScript

Optionally leverage web framework (React, Angular, Vue, etc)

Run entirely in a web browser – no (or minimal) server-side component


OAuth 2.0 implicit flow and authorization code flow

Microsoft identity platform supports both implicit flow and authorization code
flow, but authorization code flow is recommended.

Implicit flow uses iframes and cookies for silent single sign-on. Many modern browsers block third-
party cookies

Implicit flow exposes the access token

Authorization code flow addresses these issues


Microsoft Authentication Library (MSAL) JS

The easiest way to use Microsoft identity for authentication and to obtain access tokens to
authorize requests to secured endpoints in SPAs is to use the Microsoft Authentication Library
(MSAL) for JavaScript.

• MSAL.js 1.x only supports use of implicit flow

• MSAL.js 2.0 (released July 2020) supports use of authorization code flow
Azure AD app registration
SPA must have an associated Azure AD app registration to support user sign-in &
obtain access token
Implement authentication
Demo
• Single-page applications
Web apps that sign in users and call APIs
Web apps that sign-in users & call APIs

Adding authentication enables a web app access to limited profile details


Name, email, unique ID

Users authenticate in a browser

Web app redirects users to Microsoft identity to sign-in

Microsoft identity redirects users back to web app with claims about the user in an Identity token

Web app can also obtain an access token from Microsoft identity to act on the user’s behalf
OAuth 2.0 authorization code grant flow
Azure AD app registration
Web apps must have an associated Azure AD app registration to support
user sign-in & obtain access token

Ensure Redirect URI & Logout URL are set

Web app also needs a client secret


• Used by app to authenticate when exchanging
auth code for access token

After creating app, copy 3 values for use in MSAL


& code configuration:
• Tenant ID
• Client ID
• Client secret / certificate (production apps)
Signing-in & acquiring tokens

The sign-in process is handled by redirecting the user to the Azure AD sign-in page.

The sign-in process uses the values from the appsettings.json file and the configuration defined
in the previous setup to create the Azure AD URL to send the user to.

When a user signs-in to Azure AD and is redirected back to the web application, the web app uses
the MSAL.NET library to obtain an access token.
Daemon and non-interactive apps
Daemon & non-interactive apps
Some applications need to authenticate and obtain an access token to call secured endpoints without
any user interaction
• Console apps
• Services
• Web application that needs to access services but not in the context of the current user (Azure
KeyVault

These types of apps:


• Require application permissions, not delegated permissions
• Must have their permissions approved by administrators
• Are confidential client applications
• Have their own authentication credentials
Azure AD app registration

Redirect URI not required for apps


that leverage the client
credentials flow

Must upload a certificate or


create a client secret for the app
Permissions
Daemon apps can only request application permissions to
APIs

Must define all permissions required by the app in Azure AD


as application permissions

Permissions must have a tenant admin pre-consent to the app


calling the web API
• Understanding permissions and the
Permissions consent framework in the Microsoft
and consent identity platform
framework • Delegated permissions and consent
• Application permissions and consent
Understanding permissions and the consent framework
in the Microsoft identity platform
Types of permissions

Delegated permissions
• Used by apps with a signed-in user present
• Permissions provided to the app by the user so the app can act on the user’s behalf
• Doesn’t give permissions to the app
• User must have the permissions it grants to the app

Application permissions
• Used by apps that run without a signed-in user present

Effective permissions
• Permissions the app has when making requests to the target resource
• Intersection of delegated and application permissions
Effective permissions

Effective permissions are the permissions that your app will have when making requests to the
target resource.
Best practices for requesting permissions

Only ask for the permissions required for implemented functionality


• Don’t request user consent for permissions that you haven’t implemented in the app

Always request least-privileged access


• If an app needs Mail.Read, don’t request Mail.ReadWrite

Apps should gracefully handle scenarios where the user does not grant consent to the app when
permissions are requested
Permissions and consent framework
Demo
• Understanding permissions and the consent
framework in the Microsoft identity platform
Delegated permissions and consent
Delegated permissions
Delegated permissions are used by apps that have a signed-in user present

Either the user or an administrator consents to the permissions the app requests

App is then enabled to act on behalf of the signed-in user

Important to note – users do not grant apps permission; they grant the
app ability to act on their behalf

Some permissions can not be granted by a user and must be granted by an administrator:
• User grantable permissions: User.Read & User.ReadBasic.All
• Administrator grantable permissions: User.Read.All
User consent

If user / administrator hasn’t granted permission when requesting


an access token, the user is presented with the consent dialog

Selecting Accept records the consent and user won’t be


prompted for the permissions again

Two ways to request the permissions that drive what is listed in


the consent dialog:
• Static consent
• Dynamic consent
Static Consent
Permissions defined in the app registration within Azure AD admin center

Enables administrators to consent on behalf of all users in the organization


The special /.default scope

When requesting permissions, if the /.default scope represents all static permissions defined in app
registration in the Azure AD admin center

Added to simplify the migration of apps from Microsoft identity v1.0 => v2.0 endpoint

Include it on the end of the resource:


• [app id]/.default

The /.default scope must be used for apps that implement the OAuth 2.0 client credentials flow
Dynamic consent
Introduced in the Microsoft identity v2.0 endpoint

Permissions don’t need to be specified in the app registration in the Azure AD admin center (but this is
highly recommended)

Each time app requests an access token, specifies the permissions it needs on the scope property

If user hasn’t previously consented to the permission, they are prompted to accept them

Enables developers to ask users for only the permissions the app needs at that time, incrementally
asking for more permissions as needed
User consent
If the user has not previously granted the permission to the app or an administrator hasn't
consented on behalf of all user's in the organization, when a user signs-in to an app they're
prompted with the consent dialog.
Static consent
With static consent, the permissions are defined in the app's registration within the Azure AD
admin center.
Application permissions and consent
Application permissions
Some high-privilege permissions in the Microsoft ecosystem can be set to admin-restricted.

• Read all user's full profiles by using If an app requests an application permission
User.Read.All from a user, the user is notified they need an
• Write data to an organization's directory by admin to grant the permission
using Directory.ReadWrite.All
• Read all groups in an organization's directory
by using Group.Read.All
Admin consent
There's also a dedicated admin consent endpoint you can use if you would like to
proactively request that an administrator grants permission on behalf of the entire
tenant.
HTTP

GET
https://login.microsoftonline.com/{tenant}/v2.0/adm
inconsent?
client_id=6731de76-14a6-49ae-97bc-
6eba6914391e
&redirect_uri=http://localhost/myapp/permissions

&scope=https://graph.microsoft.com/calendars.rea
d%20https://graph.microsoft.com/mail.send
&state=12345
Recommendation: provide an admin experience in your app

If an app requires admin consent for to have application permissions high-privileged delegated
permissions, consider providing a special admin experience to trigger the admin consent

Reduces friction to onboarding the app


Implement Microsoft identity –
Segment 2 of 2
Secure • Overview - securing custom APIs with
custom APIs Microsoft identity
with Microsoft • Call secured APIs from web applications
identity • Call secured APIs from daemon apps
Overview – creating and securing custom APIs with
Microsoft identity
Securing web APIs with Microsoft identity

Secure custom web APIs to protect LOB systems from custom apps
Who will use your app? Microsoft
Graph

Mobile
Humans App

Employees in your org (LOB)


Employees from orgs that pay for your app (SaaS) API 1

Partners (B2B)
Web Front End
Consumers (B2C)
API 2 API 3
Terminators (Applications/Services):
On behalf of a user
By themselves

Worker role
Access web APIs with applications (terminators)
In this module we're focusing on the last option in the figure above: terminators.
Create Microsoft identity-secured web APIs

Register & configure an Azure AD Create a new web API project Code the web API project, configured
application to support Microsoft identity
Register an Azure AD application

Copy the Tenant ID & Client ID


Register a new Azure AD app Define any custom permissions
of the new app
(scopes) the web API will utilize
Protecting an API with Azure AD

Validate received access tokens in your API


• Use existing libraries and middleware (available for most platforms)

Apply & enforce permissions!


• Delegated permissions must not exceed what the signed-in user is allowed to do
Code a secure web API
The next step is to code the web API project.

Console C#
public void ConfigureServices(IServiceCollection services)
{
dotnet new webapi -o ProductCatalog services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
-au singleorg
.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"));

services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ProductCatalog",
Version = "v1" });
});
}
public List<Product> GetAllProducts()
{
HttpContext.VerifyUserHasAnyAcceptedScope(new string[] {
"Product.Read" });
return data.Products;
}
Call secured APIs from web applications
Create Microsoft identity-secured web apps
Web apps that call web APIs are confidential client applications.

Register a secret (an application password or certificate) with Azure AD


Configure web applications to call secured APIs

The next step is to create the web application that will allow the user to sign in and then access
the secured web API.

Console

dotnet new mvc --auth SingleOrg


dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.UI
Update web app to support user sign-in for Microsoft identity
Now update the project to associate it with the Azure AD app you registered for the web app.

C#
• Domain: the domain of your Azure AD tenant public void ConfigureServices(IServiceCollection services)
{
where you registered the Azure AD services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"))
application
.EnableTokenAcquisitionToCallDownstreamApi(Constants.ProductCatalogAPI.
• TenantId: the ID of your Azure AD tenant SCOPES)
.AddInMemoryTokenCaches();
where you registered the Azure AD
application services.AddControllersWithViews(options =>
{
var policy = new AuthorizationPolicyBuilder()
• ClientId: the ID of your Azure AD application .RequireAuthenticatedUser()
.Build();
• ClientSecret: the secret of your Azure AD options.Filters.Add(new AuthorizeFilter(policy));
});
application services.AddRazorPages()
.AddMicrosoftIdentityUI();
}
Add token acquisition
The next step is to create controllers to implement the pages on the site.

C# C#
[AuthorizeForScopes(Scopes = new[] { Constants.ProductCatalogAPI.CategoryReadScope

public CategoriesController(ITokenAcquisition })]


public async Task<ActionResult> Index()
tokenAcquisition) {
{ var client = new HttpClient();

this.tokenAcquisition = tokenAcquisition; var accessToken = await


} tokenAcquisition.GetAccessTokenForUserAsync(Constants.ProductCatalogAPI.SCOPES);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",
accessToken);

var json = await client.GetStringAsync(url);

var serializerOptions = new JsonSerializerOptions


{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};
var categories = JsonSerializer.Deserialize(json, typeof(List<Category>),
serializerOptions) as List<Category>;
return View(categories);
}
Call secured APIs from daemon apps
Access Microsoft identity-secured web APIs with daemon apps
Apps that run without user interaction are referred to as services or daemon
apps.

Requires administrator to grant consent for configured permissions before obtaining an access
token

Implement the OAuth 2.0 client credentials flow

Daemon app examples:


• Web applications that are used to provision or administer users or do batch processes in a directory
• Desktop applications (like Windows services on Windows or daemon processes on Linux) that do batch
jobs, or an operating system service that runs in the background
• Web APIs that need to manipulate directories, not specific users
Create daemon apps that call Microsoft identity-secured web APIs

Register a new Azure AD app and configure the app with an app secret.
Client credentials grant flow
Daemon apps implement the OAuth 2.0 client credentials grant flow to obtain an access token
from Microsoft identity.
Configure daemon apps to call secured APIs

The next step is to create the daemon app that will obtain an access token and then access the
secured web API.

Console

dotnet new console


dotnet add package Microsoft.Identity.Client
dotnet add package Microsoft.Extensions.Configuration
dotnet add package Microsoft.Extensions.Configuration.Binder
Update app to support Microsoft identity
Update the project so it will authenticate with Microsoft identity and obtain an access token, and
add code to call the web API.
C# C#
var httpClient = new HttpClient();

IConfidentialClientApplication app = var defaultRequestHeaders = httpClient.DefaultRequestHeaders;


ConfidentialClientApplicationBuilder.Create("{{CLIENT_ID}}) // add ACCEPT header if not present
if (defaultRequestHeaders.Accept == null
.WithClientSecret("{{CLIENT_SECRET}}") || !defaultRequestHeaders.Accept.Any(m => m.MediaType == "application/json")) {
.WithAuthority(new httpClient.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
Uri("https://login.microsoftonline.com/{{TENANT_ID}}")) }
.Build(); // add AUTHORIZATION header with access token
defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer",
result.AccessToken);
string[] scopes = new string[] { "api://{{CLIENT_ID}}/.default"
// call web API endpoint
}; HttpResponseMessage response = await
httpClient.GetAsync($"{{WEB_API_ENDPOINT}}/api/Categories");
if (response.IsSuccessStatusCode)
AuthenticationResult result await {
app.AcquireTokenForClient(scopes).ExecuteAsync(); string json = await response.Content.ReadAsStringAsync();
var results = JsonDocument.Parse(json);
// display results
}
Work with
users, groups, • Role-based access control in Microsoft identity
• Utilize security groups in custom apps and APIs
and roles in secured with Microsoft identity
custom apps • Leverage application roles in custom apps
and APIs
Role-based access control in Microsoft identity
Overview
Custom apps that are configured with Microsoft identity to support users signing in receive information about
the user. This includes profile information but can also include the groups they belong to or app roles they've
been assigned to.

Your custom app can use this information and, in the cases where the app has the necessary permissions,
enable the user to edit their details from within the app.
Add or delete users
To add a user to your organization, first sign-in to the Azure AD admin center and select the Users
navigation option to open the All users blade.
Restricting apps to specific users

By default, Azure AD apps allow all users in Optionally disable this by enabling the Manually assign users to the app from the
an organization to sign-in to an app “User Assignment Required” property Azure AD admin center
Role-based access control (RBAC)

RBAC helps you manage resources, what areas of an app users have access to and what they
can do with those resources.

RBAC simplifies assignment by adding users to a role

App developers can:


• Check if the signed-in user has specific roles
• Allow or block access to specific endpoints with attributes
Code configuration
With the app registered in Azure AD, the next step is to configure the web app.
C#
JSON @if (User.Identity.IsAuthenticated)
{
<div>
{ <table cellpadding="2" cellspacing="2">
"AzureAd": { <tr>
"Instance": "https://login.microsoftonline.com/", <th>Claim</th>
<th>Value</th>
"Domain": "qualified.domain.name",
</tr>
"TenantId": "22222222-2222-2222-2222-222222222222", @foreach (var claim in User.Claims)
"ClientId": "11111111-1111-1111-11111111111111111", {
"ClientSecret": "", <tr>
"CallbackPath": "/signin-oidc" <td>@claim.Type</td>
<td>@claim.Value</td>
}
</tr>
}
}
</table>
</div>
}
Utilize security groups in custom apps and APIs secured
with Microsoft identity
Manage app access with Azure AD groups
Leverage security groups within custom apps with Microsoft identity.

Groups simplify access management and granting rights to individual


users

Groups can be configured to allow users to find and join groups on their
own

Optionally automatically approve join requests, or require explicit


approval by group owners
Security groups in custom apps and APIs
Custom apps can request a user's group membership as a way to provide or restrict access to
certain functionally within the app.

JSON
{
...
"optionalClaims": {
"idToken": [
{
"name": "groups",
"source": null,
"essential": false,
"additionalProperties": [ "emit_as_roles" ]
}
],
"accessToken": [],
"saml2Token": []
}
...
}
Code configuration
In ASP.NET, you can secure a controller so only authenticated users can access it by decorating it
the method with the [Authorize] attribute.
C#

@if (User.IsInRole("22222222-2222-2222-
C# 2222-222222222222"))
{
[Authorize(Roles("22222222-2222-2222-2222-
<li class="nav-item">
222222222222"))]
<a class="nav-link text-dark" asp-area=""
public class ProductsController : Controller
asp-controller="Products" asp-
{}
action="Index">Products</a>
</li>
}
Leverage application roles in custom apps
App roles in custom apps and APIs
RBAC enables administrators to grant permissions to roles vs individuals or
groups

Administrators assign roles to users and groups to control


actions and access

Developers can securely enforce authorization in their apps


with little effort on their part

Application roles are defined in the Azure AD admin center in


the application's registration manifest
Declare roles for an application
App roles managed within an app in the Azure AD admin center

JSON
"appRoles": [
{
"allowedMemberTypes": [ "User" ],
"description": "Administrator role for Product Catalog web application.",
"displayName": "ProductAdministrators",
"id": "98ce9517-557f-4ac5-b827-f18d948ee552",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "ProductAdministrators"
},
{
"allowedMemberTypes": [ "User" ],
"description": "Viewer role for Product Catalog web application",
"displayName": "ProductViewers",
"id": "7465fed6-02cc-467c-87c2-fa6e0bf4f929",
"isEnabled": true,
"lang": null,
"origin": "Application",
"value": "ProductViewers"
}
]
Add users and groups to roles
After defining the app roles within the app's manifest, you can now add users to the role.
Code configuration
In ASP.NET, you can secure a controller so only authenticated users can access it by decorating it the method with the [Authorize] attribute.

C# C#
[Authorize(Roles = ("ProductAdministrators"))]
public ActionResult Create()
[Authorize(Roles=("ProductViewers,ProductAdministr {

ators"))] var viewModel = new ProductViewModel()


{
public class ProductsController : Controller Categories = data.Categories
};
{} return View(viewModel);
}

[Authorize(Roles = ("ProductAdministrators"))]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind("ProductName", "CategoryId")] ProductViewModel model)
{
if (ModelState.IsValid)
{
data.Products.Add(new Product()
{
Id = data.Products.Max(p => p.Id) + 1,
Name = model.ProductName,
Category = new Category { Id = model.CategoryId }
});
return RedirectToAction("Index");
}
return View(model);
}
Work with Microsoft Graph
Optimize • Microsoft Graph and query parameters
data usage • Expand related entities and search
with query content in Microsoft Graph
parameters • Reduce traffic with batched requests
Microsoft Graph and query parameters
Microsoft Graph: Gateway to your data in the Microsoft cloud

https://graph.microsoft.com
Office 365 Windows 10 Enterprise Mobility + Security
Users, Groups, Organizations Activities Azure AD
Outlook Device Relay Intune
SharePoint Identity Manager
Commands
OneDrive Advanced Threat Analytics
Teams Notifications
Advanced Threat Protection
Planner
Excel
OneNote

Mail, Calendar, Channels, Messages Identity Management Administrative Units Alerts


Contacts and Tasks Tasks and Plans Access Control Applications and Devices Policies
Sites and Lists Spreadsheets Synchronization Advanced Threat Analytics and more…
Drives and Files Notes, and more… Domains Advanced Threat Protection
Accessing the Microsoft Graph

Direct REST API


 Any platform
 Any language
 Any framework

Native SDKs
 Utilize framework & platform specific implementations
 Abstracts the details of constructing & processing REST requests over HTTP
 .NET, iOS, Android, PhP, Ruby, JavaScript, etc.
Optimize data usage with query parameters
Demo
• Use the Graph Explorer to search for content
Optimize data usage with query parameters
Demo
• Reduce traffic with batched requests
Optimize • Understand throttling in Microsoft Graph
network • Avoid throttling and implement throttling
traffic with strategies
Microsoft • Eliminate polling Microsoft Graph with
Graph the delta query
Understand throttling in Microsoft Graph
Understand throttling in Microsoft Graph

Microsoft Graph limits the number of concurrent calls to the service

 Prevents overuse of Microsoft Graph resources to maintain service health

 To maintain service health, Microsoft Graph implements a throttling approach to overuse

 When an overwhelming number of requests are received by Microsoft Graph, requests are throttled

 Throttling limits differ for each scenario and endpoints


Optimize network traffic
Demo
• Understand throttling in Microsoft Graph
Access user
• Working with users in the organization
data from
• User profiles and related users
Microsoft
• Modifying users
Graph
Working with users in the organization
Develop user-centric applications with Microsoft Graph
 Manage your organization:
 Create or delete users in your Azure AD organization
 List a user's group memberships and determine whether a user is a member of a group
 List the users who report to a user and assign managers to a user
 Upload or retrieve a photo for the user

 Work with calendars and tasks:


 List and create events on a user’s calendar
 View tasks assigned to a user
 Find free meeting times for a set of users
 Get a list of reminders set on a user's calendar

 Administer mail and handle contacts:


 List mail messages and send new mail
 Create and list user contacts and organize contacts in folders
 Retrieve and update mailbox folders and settings

 Enrich your app with user insights:


 Return documents recently viewed and modified by a user
 Return documents and sites trending around a user's activity
 List documents shared with a user through email or OneDrive for Business
Access user data from Microsoft Graph
Demo
• Working with users in the organization
User profiles and related users
User profile photos

 Profile photos can be set on the following resources in Office 365:


 User
 Groups
 Contacts

 Photos are stored as binary data that developers can convert to different formats for various
scenarios
 For example: base-64 for web
Accessing profile photos

To get a resource's profile photo, use the /photo/$value endpoint on the resource.

This returns the metadata and binary data of the photo

The same operation can be done using the Microsoft Graph .NET SDK:

C#

GraphServiceClient graphClient = GetAuthenticatedGraphClient(...);


var profilePhoto = graphClient.Me.Photo.Request().GetAsync().Result;
Modifying users
Creating users
When creating a user, you must specify the required properties for the user at a
minimum.
HTTP
POST https://graph.microsoft.com/v1.0/users
Content-type: application/json

• accountEnabled (boolean) {
"accountEnabled": true,
• displayName (string) "displayName": "Melissa Darrow",
"mailNickname": "melissad",
• mailNickname (string)
"userPrincipalName":
• passwordProfile (PasswordProfile) "melissad@M365x068225.onmicrosoft.com",
"passwordProfile" : {
• userPrincipalName (string) "forceChangePasswordNextSignIn": true,
"password": "Password1!"
}
}
Manage
group • Working with groups in the organization
lifecycle with • Uses and their groups
Microsoft • Manage group lifecycle
Graph
Working with groups in the organization
Working with groups using Microsoft Graph

Groups are collections of users and other principals that share access to resources

Microsoft Graph provides access to the following types of groups:

 Office 365 groups


 Used for collaboration on a project or team
 Share resources (conversations, files, notebooks, team sites, device management, etc)
 Also known as “Unified” groups

 Security groups
 Used to control access to resources
 Can contain Office 365 groups and other security groups
Users and their groups
Direct vs. transitive membership

 /memberOf property returns only groups the user is a direct member of

 /getMemberGroups property returns groups the user is a transitive member of

 Direct membership:
 Groups the user has been explicitly added to

 Transitive membership
 Groups the user is a member of including those via a security group that was included in another security
group that has been added to group
 Also includes groups the user has been added to through dynamic membership
Manage group lifecycle
Creating groups with Microsoft Graph
Create new groups by submitting HTTP POST to https://graph.microsoft.com/v1.0/groups & include new group
as a JSON object in the request body
C#
private static async Task<Microsoft.Graph.Group> CreateGroupAsync(GraphServiceClient
client)
Must include minimal properties: {
// create object to define members & owners as 'additionalData'
• displayName (string) var additionalData = new Dictionary<string, object>();
additionalData.Add("owners@odata.bind",
• mailEnabled (boolean) new string[] {
"https://graph.microsoft.com/v1.0/users/d280a087-e05b-4c23-b073-738cdb82b25e"
• mailNickname (string) }
);
• securityEnabled (boolean) additionalData.Add("members@odata.bind",
new string[] {
"https://graph.microsoft.com/v1.0/users/70c095fe-df9d-4250-867d-f298e237d681",
"https://graph.microsoft.com/v1.0/users/8c2da469-1eba-47a4-9322-ee0ddd24d99a"
}
Specify the new group as an Office 365 group: );
groupTypes: [“Unified”]
var group = new Microsoft.Graph.Group
{
AdditionalData = additionalData,
Description = "My first group created with the Microsoft Graph .NET SDK",
DisplayName = "My First Group",
GroupTypes = new List<String>() { "Unified" },
MailEnabled = true,
MailNickname = "myfirstgroup01",
SecurityEnabled = false
};

var requestNewGroup = client.Groups.Request();


return await requestNewGroup.AddAsync(group);
}
Deleting groups with Microsoft Graph

To delete a group, submit an HTTP DELETE request to the group endpoint.

C#
HTTP
var groupIdToDelete = "{ID}";
DELETE await
https://graph.microsoft.com/v1.0/groups/{ID} client.Groups[groupIdToDelete].Request().Dele
teAsync();
Access files
• Access and download files from OneDrive
with
• Uploading files to OneDrive
Microsoft
• Work with file relationships and trends in
Graph
OneDrive
Access and download files from OneDrive
Why integrate with OneDrive file storage in the cloud?

 Tap into billions of files

 Store your app's files in a powerful cloud

 Bring your app straight to users within OneDrive

 Work with content in formats your app understands

 Work with file content and metadata without downloading the binary

 React to file changes


Microsoft Graph Files resource

 Microsoft Graph exposes two resources when working with files:


 Drive
 DriveItem

 Both objects expose data in the following ways:


 Properties – id & name
 Facets – file & photo
 References – children & thumbnails
Accessing files for users, groups & SharePoint sites

 Accessing another user’s files (provided you have permissions)


 https://graph.microsoft.com/v1.0/users/{user-id}/drive

 Accessing files in Office 365 groups


 https://graph.microsoft.com/v1.0/groups/{group-id}/drive

 Accessing files in SharePoint Online site collections


 https://graph.microsoft.com/v1.0/sites/{site-id}/drive
Uploading files to OneDrive
Uploading small files up to 4 MB

Microsoft Graph supports uploading files up to 4 MB in size using a simple HTTP


PUT request.

HTTP HTTP

HTTP PUT HTTP PUT


https://graph.microsoft.com/v1.0/me/drive/ro https://graph.microsoft.com/v1.0/me/drive/ite
ot:/myNewSmallFile.txt:/content ms/{item-id}/content
Content-Type: text/plain Content-Type: text/plain

This is a new small file A new small file


Uploading large files greater than 4 MB
Microsoft Graph also supports uploading files larger than 4 MB up to the maximum
file size supported by OneDrive.
HTTP
HTTP
HTTP/1.1 200 OK
HTTP POST Content-Type: application/json
https://graph.microsoft.com/v1.0/me/drive/ro
ot/createUploadSession {
Content-Type: application/json "uploadUrl":
"https://sn3302.up.1drv.com/up/fe6987415ac
{ e7X4e1eF866337",
"item": { "name": "largefile.zip"} "expirationDateTime": "2019-12-
} 29T09:21:55.523Z"
}
Work with file relationships and trends in OneDrive
Files insights

Insights are relationships calculated using advanced analytics & machine learning
techniques

 Microsoft Graph includes the following insights APIs:


 Trending: documents trending around a specific user
 Used: documents viewed & modified by the user
 Shared: documents shared with a user
 Each insight record returned includes two objects:
 resourceVisualization: includes properties for displaying results (title, previewImageUrl)
 resourceReference: includes details on the returned record (URL, ID, file type)
Use change
• Overview – Microsoft Graph change
notifications
notifications
and track
• Microsoft Graph change notifications
changes with
• Track changes with Microsoft Graph
Microsoft
Graph
Overview – Microsoft Graph change notifications
Change notifications with the Microsoft Graph API

Allows applications to be notified when data changes in the Microsoft Graph

 Subscribe to particular notifications

 Combine notifications with track changes for robust data notifications

 Get notifications on messages, events, contacts, users, groups, conversations, OneDrive files,
alerts, and more
Example notification scenarios

 Translate an email when it arrives

 Start a Flow when a document is X many months old

 Create new user accounts in your application when a user joins an


organization
Developing change notifications

Create an app that will host a web API to listen for notifications.

Create a subscription to tell Microsoft Graph what entities you want to receive
notifications about and the address of your web API to post them to.
• Manage and renew subscriptions as needed

The change notifications that your app receives from Microsoft Graph can allow you
to track the changes of entities if you need to replicate data in your own system.

Must stand up a well-known and accessible HTTPS-secured endpoint to receive the


notifications.
• Use ngrok to simplify local development
Microsoft Graph change notifications
Subscribe for notifications to the Microsoft Graph API

Register Azure AD application and configure with necessary permissions.

Get an access token for Microsoft Graph.

Subscribe for the notification you would like to receive.

Respond to validation request from Microsoft Graph.

Respond to validation request from Microsoft Graph.


Change notification subscription endpoints

Microsoft Graph exposes multiple endpoints for developers to create and manage subscriptions:

• Create subscriptions
• HTTP POST https://graph.microsoft.com/v1.0/subscriptions
• Include the details of the subscription in the request body
• List subscriptions
• HTTP GET https://graph.microsoft.com/v1.0/subscriptions
• Retrieve a list of all active, non-expired, subscriptions
• Get one subscription
• HTTP GET https://graph.microsoft.com/v1.0/subscriptions/{GUID}
• Retrieve the details of a specific subscription using the subscription's ID
• Update subscription
• HTTP PATCH https://graph.microsoft.com/v1.0/subscriptions/{GUID}
• Update the expiration time of the subscription
• Delete subscription
• HTTP DELETE https://graph.microsoft.com/v1.0/subscriptions/{GUID}
• Delete an existing subscription
Use change notifications and track changes
Demo
with Microsoft Graph
• Microsoft Graph change notifications
Track changes with Microsoft Graph
Track Changes with the Microsoft Graph API

 Allows retrieving changes since you last requested them

 Available for messages, groups, users and events

 Use the /delta function to request changes

 Store returned deltaLink for subsequent requests

 Use $select to narrow what you want changes for


Use change notifications + track changes together

 For robust synchronization use notifications with track changes

 Subscribe for notifications

 When a notification is received use track changes to retrieve changes

 If a notification is missed changes will not be missed

 Add a full regular query at a long interval to be 100% certain no changes have been missed
Extend and Customize SharePoint
• Introduction to the SharePoint
Getting
Framework
started with
• Configure your Office 365 environment
SharePoint
• Configure your development
Framework
environment
Introduction to SharePoint Framework
SharePoint UX – Evolving cross versions

SharePoint SharePoint Office SharePoint SharePoint SharePoint SharePoint


Portal Server 2001 Portal Server 2003 Server 2007 Server 2010 Server 2013 Server 2016, SPO

2001 2003 2006 2009 2012 2016 …


SharePoint Framework Extensibility Principles
SharePoint Framework
Configure your Office 365 environment
Office 365 Developer Tenant Setup Steps
 Sign up for an Office 365 Developer Tenant
 Create app catalog site
 Create a new site collection for testing – dev or normal
 Use online workbench to test your code
Getting started with the SharePoint
Demo
Framework
• Configure your Office 365 environment
Configure your development environment
Open-source tooling

SharePoint Framework leverages an open source, Node.js based toolchain and embraces all web
frameworks + code editors

Build Process & Tooling Web Frameworks Code Editors

• Yeoman Templates • React • Visual Studio Code


• Gulp (task runner) • Angular • Atom
• Node.js • Knockout • Sublime
• NPM (package manager) • jQuery • Webstorm
• SystemJS • … and more… your choice! • … and more… your choice!
• Webpack
• SASS
• TypeScript
Server-side tool comparison

C#
IIS Express

MSBuild
Project Templates
Develop web
• Overview of SharePoint Framework web
parts with
parts
SharePoint
• Explore a SharePoint Framework project
Framework
Overview of SharePoint Framework web parts
Client-side web parts

They are still web Built for the modern, Runs directly inside a
parts! JavaScript-driven web SharePoint Page
Explore a SharePoint Framework project
Project Structure
 .vscode: contains Visual Studio Code integration files
 config: contains all config files
 dist: contains output from all bundle processes
 lib: created automatically on builds – contains pre-bundled built
files
 node_modules: created automatically when installing all package
dependencies with a package manager
 release: contains output from production bundle processes
 src: this is the main folder of the project, it includes the web part,
styles, and a test file
 temp: created automatically on builds - contains local dev
webserver files
Key Files – web part class
 Defines the main entry point for the web part
 Extends the BaseClientSideWebPart
 All client-side web parts must extend the
BaseClientSideWebPart class in order to be defined as a
valid web part
 Interface that defines the non-standard public properties on
the web part
 Persisted when the web part is saved / published from edit
mode
Key Files – web part manifest
 Defines the web part metadata
Key Files – SCSS file
 Defines the web part styles
Key Files – config file
 Contains information about your bundle(s), any external dependencies, localized resources
 Specifies the AMD script libraries used in the web part
Client-side Web Part Build Flow
Develop web parts with the SharePoint
Demo
Framework
• Create a SharePoint Framework client-side web
part
Leverage
• Call anonymous third-party REST APIs
Microsoft
• Call Azure AD- secured third-party APIs
Graph and
• Call Microsoft Graph in SharePoint
third-party
Framework solutions
APIs
Consume third-party REST APIs
Consume REST APIs in SPFx - Overview
 Common requirement in SPFx project is to display or interact with data external to the web part
 Data in SharePoint lists & libraries
 Data accessible via Microsoft Graph REST API
 Data accessible in external 3rd Party APIs – anonymous & secured

 SharePoint Framework provides APIs for all situations when you need to work with data sources
external to the web part
 HttpClient: for calling 3rd party REST APIs
 MSGraphClient: for calling the Microsoft Graph in the same tenant as the
SharePoint Online tenant
 AADHttpClient: for 3rd party REST APIs secured with Azure Active Directory

 Most scenarios require no extra clients / libraries are required


Call Azure AD-secured third-party REST APIs
Securing REST APIs with Azure AD
 Resources in Azure can be easily secured with Azure AD

 Requires a request to include a valid OAuth access token in the


HTTP header on request

 Similar to how existing services are secured


 SharePoint REST API
 Microsoft Graph API
 Azure Management REST API
 etc.
Calling Azure AD Secured Resources from SPFx
 Permission requests to resources are granted to special SharePoint app by tenant admin
 SharePoint Online Client Extensibility Web Application Principal
 Present in each SharePoint Online tenant

 Permissions are unique to the tenant, not the SPFx solution


 Once a permission is granted, all solutions can leverage the grant
 Permission grant is valid until revoked
 Permission grant not directly linked to the solution that requested it
 Solution installation not linked to permission grant approval / rejection
Granting Permissions to SharePoint Online
 Special SharePoint Online Azure AD app can be granted permissions to resources in multiple ways:

1. Defined within solution manifest – admin notified upon deployment to approve/reject


2. PowerShell
3. Office 365 CLI

 Ref: https://docs.microsoft.com/sharepoint/dev/spfx/use-aadhttpclient
How It Works: Calling Azure AD Secured REST APIs from SPFx
Using the Azure AD HTTP Client
TypeScript

AadHttpClient

aadHttpClientFactory
.getClient(“https://your-endpoint-uri”)
aadClient: AadHttpClient

aadClient.get(endpoint, AadHttpClient.configurations.v1)
Add SharePoint Package to SharePoint App Catalog
 Upload SharePoint packages to the app catalog

 Extra note in dialog notifies of additional step required


 While application can be installed
in SharePoint sites, it does not
have the permissions granted
that it needs to access Azure AD
protected resources
Approve / Reject with SharePoint Online API Management Page
Approve / Reject with SharePoint Online API Management Page
Leverage Microsoft Graph and third-party
Demo
APIs
• Call Microsoft Graph from SharePoint Framework
components
Build • Deploy SPFx web parts as Microsoft Teams tabs
Microsoft • Create web parts for SharePoint Online and
Teams Microsoft Teams
customizations • Client-side web part settings in Microsoft Teams
using SPFx tabs
Deploy SPFx web parts as Microsoft Teams tabs
Benefits to using SharePoint Framework to Extend Microsoft Teams
 Development model is similar to SharePoint Framework web parts

 Any web part can be exposed as a tab in Microsoft Teams

 Have difference scoping options on exposing your custom tab as a web part and tab in your tenant

 Tab executed in the context of the underlaying SharePoint site behind of the specific team

 Take advantage of any SharePoint specific APIs or functionalities


in your web part!
 Access SharePoint REST API, Microsoft Graph, Azure AD-secured Endpoints… all straight from the SPFx API
How to Surface SharePoint Framework Web Parts as Microsoft Teams
Tabs?

Specify web part


can be a tab

Create Microsoft
Teams tab images
& descriptions

Create manifest to
Microsoft Teams
app
Specify SharePoint Framework Web Part can be Microsoft Teams Tab
 Web part manifest property:
supportedHosts

 Web parts in SharePoint:


SharePointWebPart

 Tabs in Microsoft Teams:


TeamsTab
Create Microsoft Teams Tab Images
Create Microsoft Teams App manifest
 Tells Microsoft Teams about the app:
 Name and location of images
 Name and description of application
 ”About” and metadata for application
 Location of underlying application

 SharePoint Framework web parts as Teams Tabs – already have most of the information in the
SharePoint component’s manifest

 SharePoint can create and deploy Microsoft Teams manifest automatically


 Process performed within SharePoint’s App Catalog
 Dynamically creates the Microsoft Teams app manifest
 Zips up manifest + images
 Deploys to Microsoft Teams store
Build Microsoft Teams customizations using
Demo
SharePoint Framework
• Deploy SPFx web parts as Microsoft Teams tabs
Create web parts for SharePoint Online and Microsoft
Teams
SharePoint Framework & Microsoft Teams Context
 SharePoint Framework Web Parts have access to the current page context

 Provide access to the current page, site and site collection

 SharePoint Framework v1.8.0 introduced the Microsoft Teams context object

 Same Microsoft Teams context object available from the Microsoft Teams JavaScript SDK
 NPM Package: @microsoft/teams-js

 Use the presence of the Microsoft Teams context to determine if web part is running in SharePoint
or Microsoft Teams
Client-side web part settings in Microsoft Teams tabs
Custom Microsoft Teams Tab Configuration Options
 SharePoint Framework web parts have public properties
 Public properties can be made editable via the property pane
 SharePoint page must be in edit mode to edit properties
 User must have edit rights to the page to access the property pane
Property Pane Exposed in Microsoft Teams
 Web Part property pane displayed when SPFx web part installed as a tab in a Microsoft Teams team
 Accessible via the tab context menu Settings option
Extend Microsoft Teams – Segment 1 of 2
Overview of
• What are Microsoft Teams apps?
building apps
• How do you create an app for Microsoft Teams?
for Microsoft • When should you choose to build a custom Microsoft Teams app?
Teams
What are Microsoft Teams apps?
What is a Microsoft Teams app?
A Microsoft Teams app consists of three primary components:

The Microsoft Teams client (web, desktop, or mobile) provides the extensions points
and UI elements users will interact with

Teams app package creates the app installed by users:


Manifest file
Icons

Web services hosted by developers provide the APIs and logic that power the app
Where can the Teams client be extended?
There are multiple places where the Microsoft Teams client can be extended to allow users to
interact with the app

Teams app capabilities:


Tabs
Messaging extensions
Conversational bots
Webhooks and connectors

Teams app contexts:


Teams, channels and group chats
Personal apps
Messages
Microsoft Teams platform elements
The Microsoft Teams Platform provides flexible UI elements for apps to take
advantage of

Microsoft Teams platform


elements:
Cards and card actions
Task modules
Deep links
Web content pages
How do you create an app for Microsoft Teams?
Design your app
The most important step in creating a successful app for Microsoft Teams is choosing the right
combination extensibility points and UI elements to take advantage of.

Messaging Extensions - search commands are useful for allowing your users to search an external system and then share the results of that search within Teams. With cards and
card actions, you can richly format the results of that search, and allow users to do actions on the result without leaving the Microsoft Teams client.

Messaging Extensions - action commands are great for collecting information from your user in a single place, then sending that information to your web services. They excel in
scenarios where you need to create a record of some kind, or collect more than a few pieces of information as part of a single transaction.

Tabs - in groups and channels provide a shared canvas for multiple people to collaborate. You should add this to your app if you've got information or services that are applicable
to a group of people. Keep in mind that everyone is working from the same canvas, your page should be stateless and operate as a single-page app.

Tabs - in personal apps allow for a personal web-like experience. They're typically best for "hub" scenarios - "items assigned to me", or "things I've created". They can also be useful
for static content like help or about pages.

Conversational bots - in groups and channels help add additional information to a conversation that is useful for everyone (or at least most) involved. They can be used to
proactively add relevant information to the conversation, or respond to user requests ("hey bot, create a poll for where we should go to lunch"). Typically they shouldn't be used for
multi-turn conversations - use a task module to collect the information or move the conversation to a one-to-one chat instead, then insert the results back into the original
conversation.

Conversational bots - in personal apps can enable incredibly diverse workloads. Q&A bots, bots that start workflows in other systems, bots that tell jokes and bots that take notes
are just a few examples. Just remember to consider if a conversation-based interface is the best way to present your functionality.

Webhooks & Connectors are useful to allow users to subscribe a channel to notification messages from an external system.
Tools for developing apps for Microsoft Teams
Developers have multiple options for tools to support development of apps for
Microsoft Teams.
Tools for setting up and configuring your Teams app:
Yeoman Generator for Microsoft Teams
App Studio
Microsoft Teams Toolkit for Visual Studio Code or Visual Studio IDE

Tools for building your web services


- Bot Framework SDK for messaging extensions and conversational bots
- Teams JavaScript client SDK for tabs and other content pages
- A Yeoman generator for building apps in Node.js
- A set of open-source controls for your web content pages (Fluent UI)
- Ready-for-production App Templates
App studio for Microsoft Teams app development

App Studio streamlines the process


of creating manifests and packages
for Teams apps
Use App Studio to:
Create and edit app manifests
Design and preview cards
Find documentation
Access UI controls in the React control library
Options for distributing a Teams app

Three options for distributing a Microsoft Teams app:


Share app package directly
Publish app to organizational app catalog
Publish app to public App Store

All app installations in Microsoft Teams are context-specific


Task-oriented
• Overview of messaging extensions
interactions
• Action command messaging extensions
with
• Search command messaging extensions
messaging
• Link unfurling message extensions
extensions
Overview of messaging extensions
What are messaging extensions?

Messaging extensions allow users to query


your service for information (search), and
post information to your service (action).
Developers can send the results of the interaction
back to the Microsoft Teams client, typically in the
form of a richly formatted card.

Users can invoke messaging extensions from:


• The command/search bar
• The compose message area
• From a specific message
How messaging extensions work
A messaging extension consists of a web service that you host and an
app manifest, which defines where your web service is invoked from in
the Microsoft Teams client.

The web service takes advantage of the Bot Framework's messaging schema and secure
communication protocol, so you must register your web service as a bot in the Bot
Framework.

Steps to create a messaging extension:


Create and deploy your web service
Register your web service with the Bot Framework
Define messaging extension and invoke locations in the app manifest
Upload your package to Microsoft Teams
Microsoft Teams messaging extensions and action
commands
Developing action–based messaging extensions

Action commands allow developers


to present users with a modal popup
to collect or display information.

• Register extension in app manifest


• When invoked, JSON payload is sent to
your registered web service
• Web service responds with a task module
implemented as an embedded web
interface or an adaptive card
• Alt: define a static list of parameters
• Web service handles user submission of
task module.
Messaging extensions in Microsoft Teams
Demo
• Action command messaging extensions
Search command messaging extensions
What are search commands?

Search commands enable users to search


an external system for information.

• Search query is sent from Microsoft Teams to your


web service.
• Your web service responds with a list or grid of
results.
• When a user selects a result, it is added to the
compose message box as a card or text.
Developing search-based messaging extensions
Creating a search-based messaging extension involves defining the commands
for the messaging extension in the app manifest and setting up your service to
receive and respond to queries:

Define search-based messaging extension commands

Receive queries

Respond to queries
Link unfurling messaging extensions
Developing link unfurling messaging extensions

Link unfurling allows your app to


process links pasted into messages.

• Your app can register to receive an invoke


activity when URLs with a particular domain
are pasted into the compose message area.
• The invoke will contain the full URL that
was pasted into the compose message area
• You can respond with a card the user can
unfurl, providing additional information or
actions
Create
embedded
• Create a custom Microsoft Teams personal tab
web
• Create a custom Microsoft Teams channel or group tab
experiences
with tabs
Create a custom Microsoft Teams personal tab
What is a tab in Microsoft Teams?

Tabs in Microsoft Teams display web applications, hosted by the


developer, within an IFRAME in the Teams client.

Tab scope defined in app manifest:


Team (channel): Added to a channel within a team
Group chat: Can be used in group chats between 2 or more users
Personal: Available only to an individual user via app bar side navigation

Adapt existing web app experiences


Build tab from scratch
Tabs differ from web applications when browsing the same content
While Microsoft Teams tabs are webpages displayed in an iframe, there are some
differences between interacting with the web app within the Microsoft Teams client compared to just browsing t
he same content.

Tabs display web content in an IFRAME

Authentication is different

Cross-domain validation is different


Must list all domains that can be displayed in the tab

Web application style is based on the Teams client light / dark / high-contrast mode

Communication between Teams & the hosted page handled via Teams JavaScript client SDK
Overview of building a Microsoft Teams Tab

Design a great tab Develop your tab Deploy your tab


 Select relevant app functionality  HTML/JavaScript/TypeScript  Upload to Team
 Scope and focus the user experience  REST services  Upload to Tenant App Gallery
 Integrate and streamline access  Deep Linking and context  Submit to Office Store
Tabs in Microsoft Teams
Demo
• Create a custom Microsoft Teams personal tab
Create a custom Microsoft Teams channel or group tab
Comparing personal & channel tabs

Personal tabs Channel tabs


 Previously referred to as static tabs  Previously referred to as configurable tabs
 Scope = personal  Added to a channel
 Support individual user  Scope = team

 Not intended to be shared with others in a  Added as part of a chat between two or
team more users
 Displays a web page set in the manifest  Scope = groupchat

 Supports all members of a team / channel


 Displays a web page (content page) set in
the configuration page
Tab Configuration and Content

Tab Configuration Tab Content


 Configured in manifest  Rendered in IFRAME
 Displayed when Tab added to Channel  Content URL specified by configuration page or
 Displays a web page specified in the app manifest manifest
 Collect information  Inspect context for EntityId/SubEntityId
 Call setSettings() specifying ContentUrl and  Retrieve state based on Entity/SubEntity/User
Entity Id
Create
interactive
• Overview of bots in Microsoft Teams
conversational
• Bots in Microsoft Teams channels and group chats
bots for
• Proactive messages from bots
Microsoft
Teams
Overview of bots in Microsoft Teams
Overview of Bots in Teams

Bots are apps that users interact with


in a conversational way
Users can enter text or graphics or
use speech
Every interaction between a user and
a Bot generates an activity object
The Bot Framework Service sends the
activity objects between the user's
channel and the Bot
What tasks are best handled by bots?
Conversational bots in Teams apps allow users to interact with the web service through text,
interactive cards, and task modules

Types of conversations:
In a channel: threaded conversations between multiple people
• Individual interactions need to be concise; limit multi-turn interactions
• Bots have access to conversations where they are directly @mentioned
• Great for notifications, polls/surveys, and interactions with a single request/response cycle

In a group chat: non-threaded conversations between three or more people


• Bots have access to conversations where they are directly @mentioned
• Suited for similar scenarios as channel bots

In a one-on-one chat: interaction with a single user


• Diverse scenarios: Q&A, note-taking, bots that start workflows in other systems, etc.
Create
interactive
• Overview of bots in Microsoft Teams
conversational
• Bots in Microsoft Teams channels and group chats
bots for
• Proactive messages from bots
Microsoft
Teams
Overview of bots in Microsoft Teams
Overview of Bots in Teams

Bots are apps that users interact with


in a conversational way
Users can enter text or graphics or
use speech
Every interaction between a user and
a Bot generates an activity object
The Bot Framework Service sends the
activity objects between the user's
channel and the Bot
What tasks are best handled by bots?
Conversational bots in Teams apps allow users to interact with the web service through text,
interactive cards, and task modules

Types of conversations:
In a channel: threaded conversations between multiple people
• Individual interactions need to be concise; limit multi-turn interactions
• Bots have access to conversations where they are directly @mentioned
• Great for notifications, polls/surveys, and interactions with a single request/response cycle

In a group chat: non-threaded conversations between three or more people


• Bots have access to conversations where they are directly @mentioned
• Suited for similar scenarios as channel bots

In a one-on-one chat: interaction with a single user


• Diverse scenarios: Q&A, note-taking, bots that start workflows in other systems, etc.
Conversational bots in Microsoft Teams
Demo
• Creating conversational bots for Microsoft Teams
Bots in Microsoft Teams channels and group chats
Conversation bots in Microsoft Teams
Microsoft Teams sends notifications to TypeScript
your bot for events that happen in
scopes where your bot is active. export class ConvoBot extends TeamsActivityHandler {
constructor() {
super();
Example scenarios:
this.onReactionsAdded(async (context: TurnContext, next: () =>
 Trigger welcome message when your Promise<void>) => {
if (context.activity.reactionsAdded) {
bot is added to a team context.activity.reactionsAdded.forEach(async (reaction) => {
 Trigger welcome message when a if (reaction.type === 'like') {
await context.sendActivity(`Thank you!`);
new team member is added or }
removed });
}
 Trigger notifications when channels await next();
are created/renamed/deleted });
}
 When one of the bot’s messages are }
liked by users
Channel and group chat conversations with a Microsoft Teams bot
By adding the teams or group chat scope to your bot, it can be available to be installed in a team
or group chat. This allows all members of the conversation to interact with your bot by
@mentioning it.

 Work with @mentions


 Ensure your message parsing handles @<botname> mention in message the message text
 Your bot can retrieve other users mentioned in a message, and add mentions to messages it sends
 Strip mentions from message text when needed
 Retrieve mentions
 Mentions are returned in the entities object in payload. Use this to retrieve information about the user.
 Contain both the unique ID of the user and usually the name of the user mentioned
 Text of the message will include mention: <at>@John Smith<at>
Proactive messages from bots
Proactive messages

Proactive messages are when the bot creates a new message in a channel.

Possible scenarios:
 Welcome message for personal bot conversation
 Poll responses
 Notification of external events

Consider carefully when to use proactive messages


Collect input • Collecting user input with task modules
with task • Using adaptive cards and deep links in task modules
modules • Using task modules with bots
Collecting user input with task modules
What is a task module?

Task modules provide a modal popup


experience within Microsoft Teams.

Ideal experience for collecting input


from a user

Can chain multiple together to create a


wizard experience

Built on the foundation of Teams tabs – just a tab in


a popup window

Can be implemented as a web page, or Adaptive


Card
Task module structure

1. App icon
2. App short name
3. Task module’s title
4. Close/cancel button
5. Entire area available to the web page
option
6. Entire area rendered if using the Adaptive
Card option
7. Adaptive Card button
Task modules in Microsoft Teams
Demo
• Collecting user input with task modules
Using adaptive cards and deep links in task modules
Overview of adaptive cards
A card is a user-interface (UI) container for short or related pieces of information.
JSON
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.0",
"body": [
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "YouTube Video Selector",
"weight": "bolder",
"size": "extraLarge"
}]},
{
"type": "Container",
"items": [
{
"type": "TextBlock",
"text": "Enter the ID of a YouTube video to show in the task module player.",
"wrap": true
},
{
"type": "Input.Text",
"id": "youTubeVideoId",
"value": ""
}]}],
"actions": [
{
"type": "Action.Submit",
"title": "Update" }]}
Task modules and bots
Bots can invoke and process submissions from task modules

Bots differ from tabs and deep links:


 There is no user interface for a user to act on to trigger the opening of a task module
 Bots run in a service external to Microsoft Teams

Microsoft’s Bot Framework & the Microsoft Teams SDK have added support for
 Invoking task modules
 Handling the Action.Submit event where a task module submits information back to the bot

Bots can invoke task modules in one of two ways:


1. Create a deep link and embed it in a message the user can select
2. Reply/send a special type of message to the Bot Framework & Microsoft Teams
Invoking a task module from a bot
Extend Microsoft Teams – Segment 2 of 2
Connect web
services to
Microsoft • Create outgoing webhooks
Teams with • Create incoming webhooks
webhooks
and
connectors
Connect web services to Microsoft Teams with
webhooks
Webhooks and connectors in Microsoft Teams
Outgoing and incoming webhooks both allow developers to connect web
services to channels and teams inside Microsoft Teams

Two types:
Outgoing webhooks allow users to send text messages from a channel to the
developer’s web services without having to use the Microsoft Bot Framework
Incoming webhooks work as a type of connector, allowing users to subscribe to
receive notifications and messages from a developer’s web services
Process channel messages with outgoing webhooks
An outgoing webhook allows your users
to send messages from a channel to
your web service.

 Configured on a per-team basis

 Once configured, your users can @mention


your outgoing webhook to have Microsoft
Teams send the message to your service.

 Web service can respond with a text-based


message or a card
Outgoing webhooks in Microsoft Teams
Outgoing webhooks post data from Teams to any chosen service capable of accepting a JSON
payload. Once an outgoing webhook is added to a team, it acts like bot, listening in channels for
messages using @mention, sending notifications to external web services, and responding with
rich messages that can include cards and images.

Key features:
Scoped Configuration
Reactive Messaging
Standard HTTP messaging exchange
Teams API method support

Limitations
Add an outgoing webhook

Register the outgoing webhook

Authenticate messages

Respond with success or failure


Create incoming webhooks
Incoming webhooks in Microsoft Teams
Incoming webhooks function as connectors, providing a simple way for
an external app to share content in team channels. They are useful for
tracking and notification.

Teams provides a unique URL to which you send a JSON payload with
the message that you want to POST, typically in a card format.

Key features:
Scoped configuration
Secure resource definitions
Actionable messaging support
Independent HTTPS messaging support
Markdown support
Add an incoming webhook
Register the incoming webhook

Send messages to the channel from the


incoming webhook
Use the
teamwork • Use Microsoft Graph with Microsoft Teams
Microsoft • Configure a built-in tab with Microsoft Graph
Graph • Use Microsoft Graph to post to the activity feed
endpoint
Use Microsoft Graph with Microsoft Teams
Why integrate with Microsoft Teams?

Automate team lifecycles

Get work done even when no one is around

Create teams linked to your app

Deploy apps to teams

Use Microsoft Graph in any kind of app

Get notified about changes


Microsoft Graph & the teamwork endpoint

Microsoft Teams teams are founded on Microsoft 365 groups & SharePoint sites

Many API calls will use the /groups endpoint

Microsoft Graph’s teamwork endpoint: /team


Create teams (1): create Microsoft 365 group

"groupTypes":["Unified"],
Create a group using the Microsoft "mailEnabled":true, "securityEnabled":false,

Graph v1.0 `/groups` endpoint

Submit an HTTP POST


with the group's details
Create teams (2): convert a group

Once a Microsoft 365 group has been created,


https://graph.microsoft.com/v1.0/teams

you then convert it to a Microsoft Teams team


with the `/teams` endpoint. template@odata.bind https://graph.microsoft.com/v1
.0/teamsTemplates('standard'),
group@odata.bind https://graph.microsoft.com/v1.0/
Submit an HTTP POST that includes the ID of groups('groupId')

the Microsoft 365 group to convert to a team


List teams
List all teams:

https://graph.microsoft.com/v1.0/groups?$select=id,
resourceProvisioningOptions

Get a specific team:

https://graph.microsoft.com/v1.0/teams/{group-id}

List all teams the current user has joined:

https://graph.microsoft.com/v1.0/me/joinedTeams
Protected APIs in Microsoft Teams

Some Microsoft Teams APIs exposed by Microsoft Graph access sensitive data

These APIs are considered protected APIs

Require additional validation beyond the just permissions defined & consented to in Azure AD

App developers must submit request to use protected APIs


Configure a built-in tab with Microsoft Graph
Microsoft Teams built-in channel tabs

Microsoft Teams includes multiple


built-in channel tabs

Use these tabs to display rich content to your


channel members

Many tabs are configurable to specify the


contents they should display

Some support including website URLs to jump


out of Microsoft Teams and into a browser
Use Microsoft Graph’s teamwork endpoint to create and update tabs
Create and manage Microsoft Teams tabs with the teamwork endpoint

Need to know the teamsAppId of the app, and the entityId, contentUrl, removeUrl, and
websiteUrl to provide for that kind of app.

To create or configure a tab, submit an HTTP POST to the /tabs endpoint on a channel
with a payload that contains the settings to configure the tab

Working with the endpoint


Get tabs using HTTP GET
Create tabs using HTTP POST
Include a configuration object when creating or updating tabs
Microsoft Graph’s tab endpoint
HTTP
HTTP POST https://graph.microsoft.com/v1.0/teams/{groupId}/channels/{channelId}/tabs
Content-Type: application/json
{
"displayName": "Word",
"teamsApp@odata.bind" : "https://graph.microsoft.com/v1.0/appCatalogs/teamsApps/{teamsAppId}",
"configuration": {
"entityId": "CA2E9D19-3FE7-4E60-82DF-F73BD3B8D302",
"contentUrl": "https://{tenant}.sharepoint.com/sites/TestTeam/Shared
Documents/General/sample.docx",
"removeUrl": null,
"websiteUrl": null
}
}
Built-in tabs & app IDs

Microsoft Teams built-in apps have well-


known IDs for their configurable tabs

Tab IDs are defined in the installed app’s


manifest

When configuring a tab, the


teamsApp@odata.bind property tells {teamsAppId}
Microsoft Teams what tab to load

App IDs are either strings or GUIDs depending


on the app
Tab App Ids
Tab App teamsAppId
Word com.microsoft.teamspace.tab.file.staticviewer.word
Excel com.microsoft.teamspace.tab.file.staticviewer.excel
PowerPoint com.microsoft.teamspace.tab.file.staticviewer.powerpoint
PDF com.microsoft.teamspace.tab.file.staticviewer.pdf
Website com.microsoft.teamspace.tab.web
SharePoint document library com.microsoft.teamspace.tab.files.sharepoint
SharePoint list / page 2a527703-1f6f-4559-a332-d8a7d288cd88
Microsoft Stream com.microsoftstream.embed.skypeteamstab
Microsoft Forms 81fef3a6-72aa-4648-a763-de824aeafb7d
OneNote 0d820ecd-def2-4297-adad-78056cde7c78
Planner com.microsoft.teamspace.tab.planner
Power BI com.microsoft.teamspace.tab.powerbi
Tab configuration properties
App entityId contentUrl websiteUrl removeUrl
Word, Excel, Source document ID URL to the file in the underlying null null
PowerPoint, PDF SharePoint document library
Website URL URL null null
SharePoint “” URL to the underlying SharePoint null null
document library document library
SharePoint list / null null null null
page
Microsoft Stream null null null null
Microsoft Forms null null null null
OneNote null null null null
Planner null null null null
Power BI null null null null
Use Microsoft Graph to post to the activity feed
Activity feed notifications

Enables apps to notify users to


see relevant items specific to them
Anatomy of an activity feed notification
Requirements for sending activity feed notifications

1 2 3
Custom Microsoft Custom Microsoft Notification activity
Teams app must be Teams app must be types must be
installed for the associated with an registered in the
recipient of the Azure AD app custom Microsoft
notification registration Teams app’s manifest
Requirement #2: Associate Microsoft Teams apps with Azure AD apps
The first requirement is to associate the Microsoft Teams app with the Azure AD
app registration created for the app.
JSON

{
"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.8/MicrosoftTeams.schema.json",
"manifestVersion": "1.8",
...
"webApplicationInfo": {
"id": "8a2d385d-8504-43f8-a9b2-80caa44bfe22",
"resource": "api://app.contoso.com/8a2d385d-8504-43f8-a9b2-80caa44bfe22"
}
}
Requirement #3: Register the supported activity types
The third requirement is to register with Microsoft Teams the types of activities the app can send
notifications about.

JSON
{
"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.8/MicrosoftTeams.schema.json",
"manifestVersion": "1.8",
...
"activities": {
"activityTypes": [
{
"type": "userMention",
"description": "Personal Mention Activity",
"templateText": "{actor} added the {tabName} tab to the {teamName}'s | {channelName} channel"
}
]
}
}
Sending activity feed notifications
Activity feed notifications are sent to users with the Microsoft Graph's
/teams/{groupId}/sendActivityNotification endpoint using an HTTP POST.

JSON

{
"topic": {
"source": "entityUrl",
"value": "https://graph.microsoft.com/v1.0/teams/{groupId}"
},
"activityType": "userMention",
"previewText": {
"content": "New tab created"
},
"recipient": {
"@odata.type": "microsoft.graph.aadUserNotificationRecipient",
"userId": "{recipient-objectID}"
},
"templateParameters": [
{ "name": "tabName", "value": "Word" },
{ "name": "teamName", "value": "Test Team" },
{ "name": "channelName", "value": "General" }
]
}
Authentication
• Understand authentication and single sign-on in
and single-
Microsoft Teams apps
sign on in
• Single sign-on (SSO) with Microsoft Teams tabs
Microsoft
• Single sign-on (SSO) with Microsoft Teams bots
Teams
Understand authentication and single sign-on in
Microsoft Teams apps
Microsoft Teams and Single Sign-on (SSO)

Microsoft Teams SSO support for tabs, task modules, and bots

Reduces how often users are prompted to login to third-party services

SSO requirements for Teams apps:


1.Register an Azure AD application
2.Associate a Microsoft Teams app with the Azure AD application
3.Implement the code in the tab or bot to obtain an access token from Microsoft Teams
Register an Azure AD application
• Authenticate with Azure AD using a
client ID and either a client
certificate or secret.
• Specify a Redirect URL

• Must be a multitenant application

• Expose the access_as_user


permission
• Trust all Microsoft Teams client
applications
Associate the Microsoft Teams app with the Azure AD application

Link the app to the Azure AD app in


the app’s manifest
JSON

Defined in the "webApplicationInfo": {


webApplicationInfo object "id": "023adcaa-4fef-4a4d-a94a-
0cde3a0c5b31",
• Id: Azure AD application’s [client] ID "resource":
"api://app.contoso.com/023adcaa-4fef-4a4d-
• Resource: URI of the add-in as listed a94a-0cde3a0c5b31"
in the Azure AD app registration }
Implement the code in the tab or bot to obtain access tokens
This token is only used to identify the user: it won't have permissions for Microsoft Graph.

Use the access token to identify the user


Store user preferences or other information specific to the currently signed in user.

Use the access token in your own API


Implement accepted best practices when forwarding the token received from Microsoft
Teams.

Use the access token to access Microsoft Graph


Used as a “bootstrap” token to start the OAuth2 On-Behalf-Of (OBO) flow.
Single sign-on (SSO) with Microsoft Teams tabs
Understand the SSO authentication flow for tabs
1. In the tab, a JavaScript call is made to getAuthToken()
2. User is prompted to consent (if consent is required),
or to handle step-up authentication (such as two-
factor authentication).
3. Microsoft Teams requests the tab application token
from the Azure AD endpoint for the current user.
4. Azure AD sends the tab application token to the
Microsoft Teams application.
5. Microsoft Teams sends the tab application token to
the tab in response to getAuthToken() call.
6. The token is parsed in the tab application using
JavaScript to extract required information, such as
the user's email address.
*Microsoft Teams can only prompt for consent to the
OpenID profile scope, not any Microsoft Graph
permissions.
Configure the Azure AD application for SSO

All Microsoft Teams apps that implement


SSO must also have an associated Azure
AD app registered.
client ID & client certificate/secret: these are used by your app to authenticate with Azure
AD

permissions: this is a list of the API permissions your app needs the user to consent to, such
as User.Read or Mail.Read

obtain tokens with the OAuth2 implicit flow: Microsoft Teams must be able to obtain the
access tokens and ID tokens

access_as_user permission: this permission exposed by the app registration is used to grant
apps, such as Microsoft Teams, to act on the user's behalf:

preauthorize Microsoft Teams clients to act on the user's behalf: this setting removes
the requirement for users to explicitly consenting to allow Microsoft Teams to act on the
user's behalf
Unique characteristics of the Azure AD app for tabs

Microsoft Teams tabs have some


unique characteristics because
they're a web-based interactive
experience compared to the server-
side nature of bots.
The Redirect URI for the app should point to the URL
where the tab implementation is hosted.

When exposing the API permission access_as_user, the


Application ID URI should include the domain where the
tab implementation is hosted as well.
Obtain the ID token from Microsoft Teams

The next step is for your tab to obtain the initial ID token from Microsoft Teams.

TypeScript

microsoftTeams.authentication.getAuthToken({
successCallback: (result: string) => { this.ssoLoginSuccess(result) },
failureCallback: (error: string) => { this.ssoLoginFailure(error) }
});
Obtain an access token for Microsoft Graph
When you want to submit requests to Microsoft Graph from your tab, you need to obtain an
access token from Azure AD to include in your requests to Microsoft Graph.

OAuth2 on-behalf-of flow requirements:


• set the grant_type to urn:ietf:params:oauth:grant-type:jwt-bearer
• set the assertion to the ID token from Microsoft Teams
• set the requested_token_use to on_behalf_of
• Set the scope to a space-delimited list of all permissions your app needs to call Microsoft Graph
• use the registered Azure AD app's client ID and client secret to authenticate the service with Azure
AD
Single sign-on (SSO) with Microsoft Teams bots
Understand the SSO authentication flow for bots
1. The bot requests an authentication token for the bot
application. The user receives messages at all the
active user endpoints.
2. If the current user is using your bot application for
the first time, a request prompt is displayed,
requesting the user to consent or handle step-up
authentication.
3. Microsoft Teams requests the bot application token
from the Azure AD endpoint for the current user.
4. Azure AD sends the bot application token to the
Microsoft Teams application.
5. Microsoft Teams sends the token to the bot as part
of the value object returned by the invoke activity
with the name sign-in/tokenExchange.
6. The parsed token in the bot application provides the
required information, such as the user's email
address.
Configure the Azure AD app for SSO for bots
Bots have some unique characteristics
because of their server-side-based
Bots have some
interactive uniquecompared
experience characteristics
to the
because of their server-side-based
client-side nature of tabs.
interactive experience compared to the
client-side nature of tabs.
The Redirect URI for the app should point to the Azure
Bot Framework’s token endpoint:
The Redirect URI for the app should point to the Azure
https://token.botframework.com/.auth/web/redirect
Bot Framework’s token endpoint:
When exposing the API permission access_as_user, the
https://token.botframework.com/.auth/web/redirect
Application ID URI should include the string botid-
When
insteadexposing the APIwhere
of the domain permission access_as_user,
the bot the
service is hosted:
Application ID URI should include the string botid-
api://botid-023adcaa-4fef-4a4d-a94a-0cde3a0c5b31
instead of the domain where the bot service is hosted:
Configure the bot’s Oauth connection settings in Azure
api://botid-023adcaa-4fef-4a4d-a94a-0cde3a0c5b31
Bot Framework
Configure the bot’s Oauth connection settings in Azure
Bot Framework
Associate the Azure AD app with the Microsoft Teams app

First, you must associate the Azure AD app with the Microsoft Teams app.

JSON

"webApplicationInfo": { • ID: This is the client ID of the registered Azure


"id": "023adcaa-4fef-4a4d-a94a- AD application
0cde3a0c5b31", • Resource: This is the URL of the app, which is
"resource": "api://botid-023adcaa-4fef-4a4d- the same thing as the URI that was used
a94a-0cde3a0c5b31" when registering the app in Azure AD.
}
Microsoft Teams SSO bot end user experience
When a user activates the bot the first time, it will prompt for consent

When the user selects Continue, the following


events occur:
• If the bot defines a sign-in button, the sign-in
flow for bots is triggered similar to the sign-in
flow from an OAuth card button in a message
stream. The developer must decide which
permissions require user's consent.
• If the bot isn't providing a sign-in button on
the OAuth card, user consent is required for a
minimal set of permissions.

When building a bot that that requires an


authenticated user, consider using dialogs.
Coding an SSO bot for Microsoft Teams
TypeScript
This first step in the waterfall dialog prompts
the user and bot to authenticate this.addDialog(new WaterfallDialog(MAIN_WATERFALL_DIALOG, [
this.promptStep.bind(this),
this.displayMicrosoftGraphDataStep.bind(this)
Next, the login step will attempt to obtain an
]));
access token using the bot's authentication
support.
TypeScript
If successful, it uses the access token public async promptStep(stepContext: WaterfallStepContext):
obtained in the OAuth process to submit a Promise<DialogTurnResult> {
request to Microsoft Graph to display try {
information returned from Microsoft Graph. return await stepContext.beginDialog(OAUTH_PROMPT_ID);
}
catch (err) {
console.error(err);
}
return await stepContext.endDialog();
}
Coding an SSO bot for Microsoft Teams
Next, the login step will attempt to obtain an access token using the bot's authentication support. If successful, it uses the
access token obtained in the OAuth process to submit a request to Microsoft Graph to display information returned from
Microsoft Graph:
TypeScript
public async displayMicrosoftGraphDataStep(stepContext: WaterfallStepContext): Promise<DialogTurnResult> {
// get token from prev step (or directly from the prompt itself)
const tokenResponse = stepContext.result;
if (!tokenResponse?.token) {
await stepContext.context.sendActivity("Login not successful, please try again.");
} else {
const msGraphClient = new MsGraphHelper(tokenResponse?.token);

const user = await msGraphClient.getCurrentUser();


await stepContext.context.sendActivity(`Thank you for signing in ${user.displayName as string} (${user.userPrincipalName as string})!`);
await stepContext.context.sendActivity(`I can retrieve your details from Microsoft Graph using my support for SSO! For example...`);

const email = await msGraphClient.getMostRecentEmail();


await stepContext.context.sendActivity(`Your most recent email about "${email.subject as string}" was received at ${new Date(email.receivedDateTime as
string).toLocaleString()}.`);
}
return await stepContext.endDialog();
}
Thank You!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy