Forum Discussion
call Graph API from Teams Tab
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?
- Sayali-MSFTMicrosoft
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).
- vovanbCopper Contributor
Hi Alexis,
so I need to do something similar to below examples:
https://github.com/OfficeDev/Microsoft-Teams-Samples/blob/main/samples/app-complete-auth/csharp/AppCompleteAuth/helper/AuthHelper.cs
or
https://github.com/OfficeDev/Microsoft-Teams-Samples/blob/main/samples/tab-sso/csharp/TeamsTabSSO/Helper/SSOAuthHelper.cs
ThanksHi 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?tabs=aspnetcore&WT.mc_id=M365-MVP-4039677