Code Monkey home page Code Monkey logo

demo.msteams.app's Introduction

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

demo.msteams.app's People

Contributors

ardacetinkaya avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.