Forum Discussion

GSYSJobs's avatar
GSYSJobs
Copper Contributor
Jul 18, 2023

InvalidToken using v2.0 REST API

Hi, 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

 

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 verylargetoken");

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 hope I have explained well,

 

Thank you,

 

 

2 Replies

  • jhonmartin370's avatar
    jhonmartin370
    Copper Contributor

    Have you checked if the token is being passed correctly in the Authorization header? Sometimes formatting or expired tokens can cause such errorshttps://ssstok.net/ Double-check and ensure the token is valid and properly formatted. Hope this helps.

Resources