Sample code for Microsoft Teams application with SSO, Bots, Messaging extensions and other capabilities.
This lab is part of Path A, which begins with a Northwind Orders application that already uses Azure AD.
In this lab you will extend the Northwind Orders application as a personal tab in a Teams application. That means the application needs to run in an IFrame; if your app includes code that prevents this, you may need to modify it to look for the Teams referrer URL.
The Northwind Orders app doesn’t check for IFrames, but Azure AD does, so the existing site won’t work without modifications. To accomodate this and to prevent extra user logins, you’ll set this tab up to use Teams’ Azure AD Single Sign-on.
The completed solution can be found in the A02-after-teams-sso folder, but the instructions will guide you through modifying the app running in your working folder.
Note that as you complete the labs, the original app should still work outside of Teams! This is often a requirement of ISV’s who have an app in market and need to serve an existing customer base outside of Teams.
In this lab you will learn to:
The project structure when you start of this lab and end of this lab is as follows.
Use this depiction for comparison.
On your left is the contents of folder A01-begin-app
and on your right is the contents of folder A02-after-teams-sso
.
🆕 New files/folders
🔺Files changed
Project Structure Before | Project Structure After |
---|---|
A01-begin-app ├── client │ ├── components │ ├── 🔺navigation.js │ └── identity │ ├── 🔺identityClient.js │ └── userPanel.js ├── modules │ └── env.js │ └── northwindDataService.js ├── pages │ └── categories.html │ └── categories.js │ └── categoryDetails.html │ └── categoryDetails.js │ └── myOrders.html │ └── orderDetail.html │ └── orderDetail.js │ └── privacy.html │ └── productDetail.html │ └── productDetail.js │ └── termsofuse.html ├── index.html ├── index.js ├── northwind.css ├── server │ └── constants.js │ └── identityService.js │ └── northwindDataService.js │ └── server.js ├── 🔺.env_Sample ├── .gitignore ├── 🔺package.json ├── README.md |
A02-after-teams-sso ├── client │ ├── components │ ├── 🔺navigation.js │ └── identity │ ├── 🔺identityClient.js │ └── userPanel.js ├── modules │ └── env.js │ └── northwindDataService.js │ └── 🆕teamsHelpers.js ├── pages │ └── categories.html │ └── categories.js │ └── categoryDetails.html │ └── categoryDetails.js │ └── myOrders.html │ └── orderDetail.html │ └── orderDetail.js │ └── privacy.html │ └── productDetail.html │ └── productDetail.js │ └── termsofuse.html ├── index.html ├── index.js ├── northwind.css ├── 🆕manifest │ └── 🆕makePackage.js │ └── 🆕manifest.template.json │ └── 🆕northwind32.png │ └── 🆕northwind192.png ├── server │ └── constants.js │ └── identityService.js │ └── northwindDataService.js │ └── server.js ├── 🔺.env_Sample ├── .gitignore ├── 🔺package.json ├── README.md |
Microsoft Teams provides a Single Sign-On (SSO) capability so users are silently logged into your application using the same credentials they used to log into Microsoft Teams. This requires giving Microsoft Teams permission to issue Azure AD tokens on behalf of your application. In this exercise, you’ll provide that permission.
Return to the Azure AD admin portal and make sure you’re logged in as the administrator of your development tenant. Click “Azure Active Directory” 1️⃣ and then “App Registrations” 2️⃣.
Select the app you registered earlier to view the application overview.
Click “Expose an API” 1️⃣ and then “+ Add a client application” 2️⃣.
Paste the ID for the Teams mobile or desktop app, 1fec8e78-bce4-4aaf-ab1b-5451cc387264
into the flyout 1️⃣ and check the scope you created earlier 2️⃣ to allow Teams to issue tokens for that scope. Then click “Add application” 3️⃣ to save your work.
Repeat the process for the Teams web application, 5e3ce6c0-2b1f-4285-8d4b-75ee78787346
.
Microsoft Teams applications don’t run “inside” of Microsoft Teams, they just appear in the Teams user interface. A tab in Teams is just a web page, which could be hosted anywhere as long as the Teams client can reach it.
To create a Teams application, you need to create a file called manifest.json which contains the information Teams needs to display the app, such as the URL of the Northwind Orders application. This file is placed in a .zip file along with the application icons, and the resulting application package is uploaded into Teams or distributed through the Teams app store.
In this exercise you’ll create a manifest.json file and application package for the Northwind Orders app and upload it into Microsoft Teams.
Many developers use the Teams Developer Portal to create an app package; this is preferred by many enterprise developer and systems integrators. However ISV’s may want to keep the app package settings in their source control system, and that’s the approach used in the lab. It’s just a zip file; you can create it any way you want!
😎 THE TEAMS DEVELOPER PORTAL IS IMPORTANT EVEN IF YOU GENERATE YOUR OWN APP PACKAGE. Import your pacakge into the Teams Developer Portal to run validation checks prior to submitting it to the Teams app store! If you do this periodically during development you can catch issues earlier and avoid rework.
Go to your local copy of the A02-TeamsSSO
folder on your computer and copy the manifest folder into the working folder you used in the previous lab. This folder contains a template for building the manifest.json file.
In the manifest folder you just copied, open manifest.template.json in your code editor. This is the JSON that Teams needs to display your application.
Notice that the template contains tokens such as<HOSTNAME>
and <CLIENT_ID>
. A small build script will take these values from your .env file and plug them into the manifest. However there’s one token, <TEAMS_APP_ID>
that’s not yet in the .env file; we’ll add that in the next step.
Examine the staticTabs
property in the manifest. It defines two tabs, one for the “My Orders” page and one for the “Products” page. The contentUrl
is used within the Teams application, and websiteUrl
is used if Teams can’t render the tab and needs to launch it in a regular web browser. The Northwind Orders app will use the same code URL’s for both.
"staticTabs": [
{
"entityId": "Orders",
"name": "My Orders",
"contentUrl": "https://<HOSTNAME>/pages/myOrders.html",
"websiteUrl": "https://<HOSTNAME>/pages/myOrders.html",
"scopes": [
"personal"
]
},
{
"entityId": "Products",
"name": "Products",
"contentUrl": "https://<HOSTNAME>/pages/categories.html",
"websiteUrl": "https://<HOSTNAME>/pages/categories.html",
"scopes": [
"personal"
]
Now examine the webApplicationInfo
property. It contains the information Teams needs to obtain an access token using Single Sign On.
"webApplicationInfo": {
"id": "<CLIENT_ID>",
"resource": "api://<HOSTNAME>/<CLIENT_ID>"
}
Open the .env file in your working directory and add this line:
TEAMS_APP_ID=1331dbd6-08eb-4123-9713-017d9e0fc04a
You should generate a different GUID for each application you register; this one is just here for your convenience. We could have hard-coded the app ID in the manifest.json template, but there are times when you need it in your code, so this will make that possible in the future.
Run this command in your working application folder:
npm install adm-zip --save-dev
Open the package.json file in your working directory and add a script that will generate the app package. The script code is in the manifest folder you just copied, so we just need to declare it in package.json. This is what scripts
property should look like when you’re done.
"scripts": {
"start": "nodemon server/server.js",
"debug": "nodemon --inspect server/server.js",
"db-download": "node northwindDB/dbDownload.js",
"package": "node manifest/makePackage.js"
},
Now you can build a new package at any time with this command:
npm run package
Go ahead and run it, and two new files, manifest.json and northwind.zip (the app package) should appear in your manifest folder.
Create a file called teamsHelpers.js
in the client/modules folder
, and paste in this code:
// async function returns true if we're running in Teams
export async function inTeams() {
return (window.parent === window.self && window.nativeInterface) ||
window.navigator.userAgent.includes("Teams/") ||
window.name === "embedded-page-container" ||
window.name === "extension-tab-frame";
}
This function will allow your code to determine if it’s running in Microsoft Teams, and is used in this and future labs.
NOTE: There is no official way to do this with the Teams JavaScript SDK v1. The official guidance is to pass some indication that the app is running in Teams via the app’s URL path or query string. This is not a single-page app, however, so we’re using a workaround to avoid updating every page to generate hyperlinks that support Teams-specific URLs. This workaround is used by the yo teams generator, so it’s well tested and in wide use, though not officially supported.
Open the client/identity/identityClient.js
file and add these import statements near the top.
import { inTeams } from '/modules/teamsHelpers.js';
import 'https://statics.teams.cdn.office.net/sdk/v1.11.0/js/MicrosoftTeams.min.js';
The first import, of course, is the inTeams() function we just added. It’s a JavaScript module so there is no bundling; the browser will resolve the import at runtime.
The second import will load the Teams JavaScript SDK, which creates a global object microsoftTeams
that we can use to access the SDK. You could also load it using a <script>
tag or, if you bundle your client-side JavaScript, using the @microsoft/teams-js npm package.
Now modify the getAccessToken2()
function to include this code at the top:
if (await inTeams()) {
microsoftTeams.initialize();
const accessToken = await new Promise((resolve, reject) => {
microsoftTeams.authentication.getAuthToken({
successCallback: (result) => { resolve(result); },
failureCallback: (error) => { reject(error); }
});
});
return accessToken;
} else {
// existing code
}
This code checks to see if it’s running in Teams and if so, uses the Teams JavaScript SDK’s getAuthToken()
function to get the access token needed to call the server.
The completed getAccessToken2()
function should look like this:
async function getAccessToken2() {
if (await inTeams()) {
microsoftTeams.initialize();
const accessToken = await new Promise((resolve, reject) => {
microsoftTeams.authentication.getAuthToken({
successCallback: (result) => { resolve(result); },
failureCallback: (error) => { reject(error); }
});
});
return accessToken;
} else {
// If we were waiting for a redirect with an auth code, handle it here
await msalClient.handleRedirectPromise();
try {
await msalClient.ssoSilent(msalRequest);
} catch (error) {
await msalClient.loginRedirect(msalRequest);
}
const accounts = msalClient.getAllAccounts();
if (accounts.length === 1) {
msalRequest.account = accounts[0];
} else {
throw ("Error: Too many or no accounts logged in");
}
let accessToken;
try {
const tokenResponse = await msalClient.acquireTokenSilent(msalRequest);
accessToken = tokenResponse.accessToken;
return accessToken;
} catch (error) {
if (error instanceof msal.InteractionRequiredAuthError) {
console.warn("Silent token acquisition failed; acquiring token using redirect");
this.msalClient.acquireTokenRedirect(this.request);
} else {
throw (error);
}
}
}
}
Finally, update the logoff function to disable logging off if it’s running in Teams.
export async function logoff() {
getLoggedInEmployeeIdPromise = null;
getAccessTokenPromise = null;
if (!(await inTeams())) {
msalClient.logoutRedirect(msalRequest);
}
}
Microsoft Teams already has multiple levels of navigation, including multiple tabs as configured in the previous exercise. So the applications’ built-in navigation is redundant in Teams.
To hide the built-in navigation in Teams, open the client/components/navigation.js
file and add this import statement at the top.
import { inTeams } from '../modules/teamsHelpers.js';
Now modify the connectedCallback()
function, which displays the navigation web component, to skip rendering if it’s running in Teams. The resulting function should look like this:
async connectedCallback() {
if (!(await inTeams())) {
let listItemHtml = "";
topNavLinks.forEach(link => {
if (window.location.href.indexOf(link.url) < 0) {
listItemHtml += '<li><a href="' + link.url + '">' + link.text + '</a></li>';
} else {
return listItemHtml += '<li><a href="' + link.url + '" class="selected">' + link.text + '</a></li>';
}
});
this.innerHTML = `
<ul class="topnav">${listItemHtml}</ul>
`;
}
}
NOTE: Web components are encapsulated custom HTML elements. They’re not a Teams thing, nor do they use React or another UI library; they’re built right into modern web browsers. You can learn more in this article
Now it’s time to run your updated application and run it in Microsoft Teams. Start the application with this command:
npm start
In the Teams web or desktop UI, click “Apps” in the sidebar 1️⃣, then “Manage your apps” 2️⃣. At this point you have three choices:
In this case, choose the first option 3️⃣.
Navigate to the Northwind.zip file in your manifest directory and upload it. Teams will display the application information; click the “Add” button to install it for your personal use.
The application should appear without any login prompt. The app’s navigation should not be displayed; instead users can navigate to “My Orders” or “Products” using the tabs in the Teams app.
CHALLENGE: You might have noticed the logout button doesn’t do anything in Teams! If you wish, hide the logout button just as you hid the navigation bar. The code is in client/identity/userPanel.js.
For the latest issues, or to file a bug report, see the github issues list for this repository.
Single sign-on (SSO) support for Tabs
After completing this lab, you may continue to the next lab in this learning path, A03-after-apply-styling: Teams styling and themes.