Forum Discussion

vovanb's avatar
vovanb
Copper Contributor
Jul 04, 2023

call Graph API from Teams Tab

I am using https://github.com/OfficeDev/Microsoft-Teams-Samples/tree/main/samples/bot-task-module/csharp for Teams Tab. I want to call Graph API for notification.

So I found https://github.com/OfficeDev/TeamsFx/wiki/Develop-single-sign-on-experience-in-Teams which show me how to get token :

function getSSOToken() {
  return new Promise((resolve, reject) => {
    microsoftTeams.authentication
      .getAuthToken()
      .then((token) => {
        resolve(token);
      })
      .catch((error) => {
        alert(error);
        reject("Error getting token: " + error);
      });
  });
}

 It successfully return token and pass it  as accessToken to below method from https://github.com/OfficeDev/microsoft-teams-sample-complete-node/blob/master/src/views/tab-auth/simple.hbs

 

 

 

 

function getUserProfile(accessToken) {
                $.ajax({
                    url: "https://graph.microsoft.com/v1.0/me/",
                    beforeSend: function(request) {
                        request.setRequestHeader("Authorization", "Bearer " + accessToken);
                    },
                    success: function (profile) {
                        $("#profileDisplayName").text(profile.displayName);
                        $("#profileJobTitle").text(profile.jobTitle);
                        $("#profileMail").text(profile.mail);
                        $("#profileUpn").text(profile.userPrincipalName);
                        $("#profileObjectId").text(profile.id);
                        $("#divProfile").css({ display: "" });
                        $("#divError").css({ display: "none" });
                    },
                    error: function (xhr, textStatus, errorThrown) {
                        console.log("textStatus: " + textStatus + ", errorThrown:" + errorThrown);
                        $("#divError").text(errorThrown).css({ display: "" });
                        $("#divProfile").css({ display: "none" });
                    },
                });
            }

 

 

 

 

But it returns me 401 Unauthorized.

What is the problem?

I saw many examples using graphAPI with https://learn.microsoft.com/en-us/microsoftteams/platform/toolkit/teamsfx-sdkbut all examples for React. How I can use it with my sample?

Can you provide example for using Graph API within Teams Tab and not React?

4 Replies

Resources