Office API getAccessTokenAsync result yields InvalidAuthenticationToken response from Graph - microsoft-graph-api

i have been trying to tackle this issues for a while now, i am workin on an Office-js addin for Outlook and is trying to access Microsoft Graph data through my addin.
But i have been unable to authenticate the token i recieve from getAccessTokenAsync.
If i attempt to use the authenticator from Office-JS-Helpers i can get access, but i would prefer to use the built in function of the addin for it.
the code i am trying to use is this:
Office.initialize = () => {
var options = { forceAddAccount: true, forceConsent: true } as Office.AuthOptions;
Office.context.auth.getAccessTokenAsync(options, getAccessTokenAsyncCallback);
}
function getAccessTokenAsyncCallback(accessTokenResponse) {
console.log(accessTokenResponse.value)
client = MicrosoftGraph.Client.init({
authProvider: (done) => {
done(null, accessTokenResponse.value);
},
debugLogging: false
})
client.api("/me")
.get((err, res, rawResponse) => {
console.log(err)
console.log("rawResponse")
console.log(rawResponse)
})
}
and my WebApplicationInfo in my manifest is:
<WebApplicationInfo>
<Id>{AppUID}</Id>
<Resource>api://localhost:3000/{AppUID}</Resource>
<Scopes>
<Scope>profile</Scope>
<Scope>user.read</Scope>
</Scopes>
</WebApplicationInfo>
</VersionOverrides>
and the rights has been set up in my app on the Application Registration Portal.
as far as i can see when validating/decoding the JSON Web Token i recieve from getAccessTokenAsync, it should be valid.
but whenever i try to connect using this token i get this response:
{
"statusCode": 401,
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"requestId": "4a0ce952-0e90-XXXXXXXXX-db20c6cca94e",
"date": "2018-08-30T05:37:43.000Z",
"body": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure.",
"innerError": {
"request-id": "4a0ce952-0e90-XXXXXXXXX-db20c6cca94e",
"date": "2018-08-30T07:37:43"
}
}
}
i simply can't figure out what the issue is here, am i wrong in that the token returned from getAccessTokenAsync is the one i need for this?
oh yes and i am running up against an Office365 environment with Outlook 2016 version 1807 build 10325.20118 click to run

The token that is returned by getAccessTokenAsync, called the bootstrap token, does NOT give your add-in access to MS Graph directly. Instead it gives the Office host application, Outlook in this case, access to your add-in's web application. Your add-in's web application then uses that token to get an access token to Microsoft Graph. It does this by using the "on behalf of" OAuth flow. Please see the extensive documentation at this node: SSO in Office Add-ins and, for Outlook-specific guidance, also see Authenicate a user in an Outlook Add-in with an SSO token.

Related

Microsoft Graph API: Access token validation failure. Invalid audience

I am trying to migrate my app from Office 365 REST v2.0 to Microsoft Graph (v1.0). The token exchange seems to be working but as soon as I am trying to call an API, I am getting the following error:
(
[errorNumber] => 401
[error] => Request returned HTTP error 401
[message] => {
"error": {
"code": "InvalidAuthenticationToken",
"message": "Access token validation failure. Invalid audience.",
"innerError": {
"date": "2021-03-16T15:36:21",
"request-id": "dda1e33a-2774-4986-8c45-1487404fbb72",
"client-request-id": "e842d9a8-d71b-0563-f1ce-e58052e5bdb9"
}
}
}
)
The access_token has the following audience:
"aud": "https://outlook.office.com"
Here is the endpoint that I am using:
https://login.microsoftonline.com/common/oauth2/v2.0/token
Payload:
grant_type=authorization_code
&code=0.AR8A3XwQy0FAmkSxxxx
&redirect_uri=https%3A%2F%2Fxxx.com%2Fproxy%2Foffice365authorize
&client_id=e2147faf-87f0-4e7f-xxxx-xxxxxxxxxxx
&client_secret=xxxxxxxxxxxx
Any hint would be greatly appreciated, thanks!
This means your token has the wrong audience, to call the Micrsoft Graph API, you need to get the token for Microsoft Graph i.e. the access token needs the "aud": "https://graph.microsoft.com".
Looks you are using the AAD auth code flow to get the token, so when you request an authorization code, use the scope with https://graph.microsoft.com/.default.
https://login.microsoftonline.com/common/oauth2/authorize?
client_id=xxxxx
&response_type=code
&redirect_uri=xxxxxx
&response_mode=query
&scope=https://graph.microsoft.com/.default
&state=12345
Also use scope=https://graph.microsoft.com/.default when requesting the token.
POST https://login.microsoftonline.com/common/oauth2/v2.0/token
client_id=xxxxxx
&scope=https://graph.microsoft.com/.default
&code=0.AR8A3XwQy0FAmkSxxxx
&redirect_uri=xxxxxx
&grant_type=authorization_code
&client_secret=xxxxx
To call the API successfully, also make sure you have grant correct Delegated Microsoft Graph API permissions for your client app depends on the API you want to call, e.g. if you want to call List users, you need the permissions here.

Microsoft Graph API Errors for ServiceNow

I am integrating ServiceNow with Teams specifically to push notifications to users and channels using microsoft graph api.
Issue #1 -
I have configured an OAuth profile for azure app to utilize microsoft graph API, setup required API permissions and calling various chat related API functions. For 'Create Chat' request I am getting below error:
responseBody: {
"error": {
**"code": "UnknownError",**
"message": "",
"innerError": {
"date": "2021-01-29T09:20:53",
"request-id": "90a99bf5-048f-445b-b58c-ee46fc30edf3",
"client-request-id": "90a99bf5-048f-445b-b58c-ee46fc30edf3"
}
}
}
API call -
var restMessage = new sn_ws.RESTMessageV2();
restMessage.setHttpMethod("POST");
restMessage.setEndpoint("https://graph.microsoft.com/beta/chats");
restMessage.setRequestHeader('Content-Type', 'application/json');
restMessage.setRequestHeader('Authorization', 'Bearer ' + retrieveToken()); //retrieveToken() function creates access token.
restMessage.setAuthenticationProfile('oauth', 'a5325df007022010f60df7fc7c1ed0a2');
restMessage.setRequestBody(global.JSON.stringify(
{"chatType": "oneOnOne","members":
[
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user#odata.bind": "https://graph.microsoft.com/beta/users('<userID>')"
},
{
"#odata.type": "#microsoft.graph.aadUserConversationMember",
"roles": ["owner"],
"user#odata.bind": "https://graph.microsoft.com/beta/users('<userID>')"
}
]
}
));
var response = restMessage.executeAsync();
var responseBody = response.getBody();
gs.info('responseBody: '+responseBody);
Most of the suggestions are to set appropriate API permissions. This is already set correctly on Azure (both delegated and apppication permissions) and in OAuth entity scope in servicenow.
Issue #2 -
For the same setup instead of usign scripted API, I defined REST Message record and trying to get the token by clicking 'Get OAuth Token' related link and getting following error:
https://dev72030.service-now.com/oauth_redirect.do?error=invalid_client&error_description=AADSTS650053%3a+The+application+%27msgraph-client-app%27+asked+for+scope+%27**Chat.Read.All%27+that+doesn%27t+exist+on+the+resource**+%2700000003-0000-0000-c000-000000000000%27.+Contact+the+app+vendor.%0d%0aTrace+ID%3a+b0b9ff39-fd1a-49c9-85fa-3c8c71943600%0d%0aCorrelation+ID%3a+9c276922-3a77-4cc1-890b-23177ffd1845%0d%0aTimestamp%3a+2021-01-29+10%3a31%3a27Z&state=-1877865371#
This say I need to set 'Chat.Read.All' API permission. This is already provided on both sides, Azure app and OAUth profile in SNOW.
What am I missing
Could you please check this docs? For second issue: Could you please check the permissions on src by going through the jwt.io

Unknown Error when sending/replying to message on MS Teams using Graph API

I am trying to send a message or reply to a message using Graph APIs for MS Teams. I have the correct permissions set and also have access to Protected APIs (if thats a concern).
The APIs I use to send messages are for both channel and 1:1 chat message.
POST URL Request:
https://graph.microsoft.com/beta/chats/{chat-id}/messages/{message-id}/replies
https://graph.microsoft.com/beta/chats/{chat-id}/messages/
https://graph.microsoft.com/beta/users/{user-id}/chats/{chat-id}/messages/
https://graph.microsoft.com/beta/teams/{team-id}/channels/{channel-id}/messages/{message-id}/replies
https://graph.microsoft.com/beta/teams/{team-id}/channels/{channel-id}/messages
Permissions set are ChannelMessage.Send, Group.ReadWrite.All, ChatMessage.Send for both delegated and application level.
I use a 2-step process to authorize the client /authorize and then /adminconsent.
When trying to post message I always get "UnknownError" and empty message with 401 status code.
{
"error": {
"code": "UnknownError",
"message": "",
"innerError": {
"date": "2020-07-10T04:58:06",
"request-id": "ff58128b-585b-4242-99c4-011c8e537d94"
}
}
}
Is this some issue with my app or from MS graph side?
Issue was with the access token. Using app-only permissions to send message is not supported.
Ref: https://github.com/microsoftgraph/microsoft-graph-docs/issues/8998

Using the Microsoft Team Beta API, provisioning Teams

I have been trying to use the Graph API, beta version, and am able to create an office 365 group , but so far no luck with adding a Microsoft Team to the group.
When i use the beta API i will get a code InvalidRequest, "Calling this API using MSGraph Application Permissions is not supported."
The request i am sending is a PUT with "https://graph.microsoft.com/beta/groups/{id}/team" with id the group id. Also i am sure the bearer token is ok, since other requests such as creating an office 365 group work fine.
Setting delegated permissions in Azure app registration or granting permissions didnt seem to work. Is this a beta issue for now or is there something else i should be looking for?
See the below error as example :
{
"error": {
"code": "InvalidRequest",
"message": "Calling this API using MSGraph Application Permissions is
not supported.",
"innerError": {
"request-id": "c4c28d6c-e7f2-4817-bdc7-c5985de61c92",
"date": "2018-06-19T19:18:22"
}
}
}
Regards,
Jos Eilers
App-only permissions are not currently supported. It only works with delegated permissions and that too for work or school accounts. Wont work with Personal MS account
At my end, I am making a PUT request to the /beta/groups/<group id>/team endpoint with the below mentioned payload and it works:
{
"memberSettings": {
"allowCreateUpdateChannels": true
},
"messagingSettings": {
"allowUserEditMessages": true,
"allowUserDeleteMessages": true
},
"funSettings": {
"allowGiphy": true,
"giphyContentRating": "strict"
}
}
reference - Create team - Beta documentation

InvalidAuthenticationToken Error : when Using office365 planner Tasks API

I am trying to get my office365 planner task using the Microsoft Graph API but I am getting below error:
GET https://graph.microsoft.com/beta/me/tasks
{
"error": {
"code": "InvalidAuthenticationToken",
"message": "Bearer access token is empty.",
"innerError": {
"request-id": "4f209643-f3f6-4256-87b7-cf4f2fd489eb",
"date": "2016-05-16T09:03:33"
}
}
}
The error message is pretty self-explanatory,
"message": "Bearer access token is empty."
You need to be authenticated before you can make this RESTful API call.
If you're developing your own app, follow this tutorial to learn about OAuth2 workflow,
http://graph.microsoft.io/en-us/docs/platform/rest
If you're using Graph Explore, make sure you're logged in before call that API.
I use this Controller's action code for granting admin consent:
//<Summary>
//Used to grant admin consent to Azure AD apps
//</Summary>
public virtual ActionResult AdminConsentApp()
{
string strResource = "https://graph.microsoft.com";
string strRedirectController = "https://localhost:[my local debug port number]";
string authorizationRequest = String.Format(
"https://login.windows.net/common/oauth2/authorize?response_type=code&client_id={0}&resource={1}&redirect_uri={2}&prompt={3}",
Uri.EscapeDataString(SettingsHelper.ClientId),
Uri.EscapeDataString(strResource),
Uri.EscapeDataString(String.Format("{0}", strRedirectController)),
Uri.EscapeDataString("admin_consent")
);
return new RedirectResult(authorizationRequest);
}
Hope this help,
Cheers, Danfer.

Resources