call Graph API from Teams Tab

Copper Contributor

I am using sample application for Teams Tab. I want to call Graph API for notification.

So I found example 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 example:

 

 

 

 

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 teamsfx sdk but 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

@vovanb -Thanks for reporting your issue.
We will check this at our end and will get back to you.

Hi @vovanb,

You cannot use the token returned by getAuthToken directly to interact with Microsoft Graph. As mentioned in this documentation 

The token contains some claims about the user's identity. You have to convert the token to an access token with your backend (similar to "on behalf of" OAuth flow).

Hi @vovanb,

 

Yes, if your backend is implemented with ASP .net core, you have middleware to simplify all the process https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-web-api-call-api-call-api?...