I am trying to make CRUD operations of the TermStore using the v2.0 REST API. But I am having problems with the token. I can generate the token correctly but when I try to use it, for example on a GET call to get the groups of the TermStore it simply appears the next error
{
"error": {
"code": "unauthenticated",
"innerError": {
"code": "invalidToken"
},
"message": "The provided token is invalid"
}
}
I gave maximum permissions to the app, because maybe it was a problem of not enough permissions I've tried giving both types of permissions, Application and Delegated
Obviously I have granted admin consent.
This is how I fetch the token:
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Cookie", "fpc=YOUR_FPC_COOKIE; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd");
var formdata = new FormData();
formdata.append("grant_type", "client_credentials");
formdata.append("client_id", "myID");
formdata.append("client_secret", "mySecret");
formdata.append("scope", "https://contoso.sharepoint.com/.default");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: new URLSearchParams(formdata),
redirect: 'follow'
};
fetch("https://login.microsoftonline.com/myTenantID/oauth2/v2.0/token", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
It works fine, It returns me a token that expires in one hour (obviously I refresh the token every hour, I still do it manually because first i want to have it working well).
But when using the token appears the error that I previously mentioned. This is the complete GET call:
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer verylongtoken");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://contoso.sharepoint.com/_api/v2.1/termstore/groups", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I've searched similar questions like
Invalid Audience URI error Service to Service application, onedrive for business
or
Sharepoint Online REST API with Azure AD v2.0 authentication
and
How to get access token without sign-up or sign-in to web app?
I've tried all the solutions but nothing.
I also have created an Application ID URI but doesn't work neither. I don't know what else to try
Should I try to work with the Microsoft Graph API instead of the SharePoint API? I know that in the past you couldn't work with Term Store but now the permission TermStore.ReadWrite.All exist, so If you think is a viable option let me now.
I hope I have explained well,
Thank you,
Should I try to work with the Microsoft Graph API instead of the SharePoint API?
Yes, very much so. For example, for the request in your example, you'd use List termStore groups.