Skip to content

MS Teams Tab application development demonstration with some Graph API calls.

License

Notifications You must be signed in to change notification settings

ardacetinkaya/Demo.MSTeams.App

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

15 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Demo.MSTeams.App

This repository is a simple demonstration of Microsoft Teams Tab Application model with current ASP.NET Core React App template. This repository is kind of a demo to integrate a web application into MS Teams.

Basically you can see usage of MS Teams Javascript client SDK usage and some approaches to use Microsoft Graph API. For initial installation of SDK, check Teams Javascript client SDK

image

With Microsoft Graph API calls some additional actions can be executed. Tabs application model for Microsoft Teams supports single sign-on (SSO). So logged user in MS Teams can be also a logged-in user for your application. To have this support, you need to define a AAD application in you M365 tenant. Create your AAD application

When you have created AAD application, in manifest file additional definition should be done to attach MS Teams app. with AAD application.

"webApplicationInfo": {
  "id": "00000000-0000-0000-0000-000000000000",
  "resource": "api://subdomain.example.com/00000000-0000-0000-0000-000000000000"
}

When you are ready with development environment, first you need to import required @microsoft/teams-js package.

import * as microsoftTeams from "@microsoft/teams-js";

After initializing the SDK, any SDK methods can be executed in required places in code for example; for a component getting context can be done is componentDidMount()

componentDidMount() {
        // .initialize() method is required.
        microsoftTeams.initialize();

        microsoftTeams.getContext((context) => {
            //You can check context's other properties to see what you have
            microsoftTeams.authentication.getAuthToken({
                successCallback: (token) => {
                    microsoftTeams.appInitialization.notifySuccess();
                    //Now you have MS Teams user identification token
                    //You can use this token to identify your self within GraphAPI
                    //When calling an API from GraphAPI you need to create/have an authoraztion token for Graph API
                },
                failureCallback: (error) => {
                    microsoftTeams.appInitialization.notifyFailure({
                        reason: microsoftTeams.appInitialization.FailedReason.AuthFailed,
                        error,
                    });
                }
            });

        });
    }

MS Teams' authentication token is not a valid token for Graph API calls. So to make a Graph API calls, first you need the proper token. In this repository with additional back-end API call, MS Teams identification token is used to have proper Graph API token and to have Graph API request.

microsoftTeams.getContext((context) => {
            this.setState({ userName: context.userObjectId });
            microsoftTeams.authentication.getAuthToken({
                successCallback: (token) => {
                    microsoftTeams.appInitialization.notifySuccess();
                    //With MS Teams' user token, some back-end API call is done
                    //Within this call, this token is used to have a proper Graph API token
                    //and a GET request is done to the 'graph/me' endpoint.
                    //Then .displayName property is set in component state
                    fetch(`api/graph/beta/me`,
                        {
                            method: "GET",
                            headers: {
                                "Authorization": `${token}`
                            }
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.error) {
                                console.error("!!!ERROR!!!");
                                console.error(data.error);
                            }
                            else {
                                console.log(data);
                                this.setState({ userName: data.data.displayName });
                            }

                        })
                        .catch(error => {
                            console.error('Unable to get user info', error);

                        });
                },
                failureCallback: (error) => {
                    microsoftTeams.appInitialization.notifyFailure({
                        reason: microsoftTeams.appInitialization.FailedReason.AuthFailed,
                        error,
                    });
                }
            });

To see back-end API check GraphController.cs. Basically some custom GraphService.cs is injected into controller with a authentication provider, GraphAuthenticator.cs with Microsoft.Graph APIs

To authenticate for Graph API call, there are some different approaches and providers. You can check here for more detailed info. In this repository you can find additional provider approaches with a simple code but for this demo following DelegateAuthenticationProvider() is used with MS Teams' user token with Microsoft.Identity.Client

     client = new GraphServiceClient(new DelegateAuthenticationProvider(
     async (requestMessage) =>
     {
         try
         {
             // "token" is MS Teams' user token
             var userAssertion = new UserAssertion(token, "urn:ietf:params:oauth:grant-type:jwt-bearer");

             var clientApplication = ConfidentialClientApplicationBuilder.Create(_clientId)
                  .WithRedirectUri(_redirectUri)
                  .WithTenantId(_tenantId)
                  .WithClientSecret(_clientSecret)
                  .Build();

             var result = await clientApplication.AcquireTokenOnBehalfOf(_defaultScope, userAssertion)
                 .ExecuteAsync();

             requestMessage.Headers.Authorization =
                 new AuthenticationHeaderValue("Bearer", result.AccessToken);
         }
         catch (Exception ex)
         {
             Logger.LogError(ex, ex.Message);
             throw;

         }


     }));

To add an application to Microsoft Teams, a manifest file is required. This manifest file defines some properties for the application. You can check full manifest file description here.

For this repository check more basic and simple version ---> manifest.json

References