Server to Server Endpoint request unauthorised

Hi All,

Im creating a Analytics tool currently and I have managed to get my access token from the server and then validated it. Now im trying to make a request to the API but Im getting Unauthroized error in my console.

Im using JavaScrip on NodeJS to run the server.


async function RequestStreams() {
  got({
    url: "https://api.twitch.tv/helix/channels?broadcaster_id=44445592",
    method: "GET",
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer `+ accessToken
    },
    responseType: "json"
}).then(resp => {
  console.log("Ok", resp.body);
  if (resp.body.expires_in <= 3600) {
      twitch.makeClientCred();
  } else {
      // it"s ok
  }
}).catch(err => {
  console.log('Error Time!')
  console.error(err);
});
}

Above is the function im using to try and get a broadcasters channel but I have tried it with getting streams, channels and various other end points but get HTTPError: Response code 401 (Unauthorized) in the console.

Any help would be appreciated.

You need to not just read the HTTP Error code, but the Error/body message as well, as that covers what the problem is.

You are not sending a Client-ID Header and this is required

Updated the code:


async function RequestStreams() {

  got({

    url: "https://api.twitch.tv/helix/streams/metadata",

    method: "GET",

    headers: {

        'Client-ID': TwitchClientID

    },

    responseType: "json"

}).then(resp => {

  console.log("Ok", resp.body);

  if (resp.body.expires_in <= 3600) {

      twitch.makeClientCred();

  } else {

      // it"s ok

  }

}).catch(err => {

  console.log('Error Time!')

  console.error(err);

});

}

And the Error I get is


Error Time!
HTTPError: Response code 404 (Not Found)
    at onResponse (D:\Twitch API Development\TwitchAppAnalytics\node_modules\got\dist\source\as-promise\index.js:124:28)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: undefined,
  timings: {
    start: 1592764794808,
    socket: 1592764794808,
    lookup: 1592764794808,
    connect: 1592764794817,
    secureConnect: 1592764794839,
    upload: 1592764794840,
    response: 1592764794989,
    end: 1592764794990,
    error: undefined,
    abort: undefined,
    phases: {
      wait: 0,
      dns: 0,
      tcp: 9,
      tls: 22,
      request: 1,
      firstByte: 149,
      download: 1,
      total: 182
    }
  }
}

You pasted the error message twice :smiley:

Edit after paste fixin, since I was super quick

    url: "https://api.twitch.tv/helix/streams/metadata",

    method: "GET",

    headers: {

        'Client-ID': TwitchClientID

    },

metadata is removed…

This doesn’t match your OP

async function RequestStreams() {
  got({
    url: "https://api.twitch.tv/helix/channels?broadcaster_id=44445592",
    method: "GET",
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer `+ accessToken
    },
    responseType: "json"
})

This

    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer `+ accessToken
    },

becomes

    headers: {
        'Content-Type': 'application/json',
        'Client-ID': clientID,
        'Authorization': `Bearer `+ accessToken
    },
1 Like

Hi, Thanks for the help so far.

Im live working on the code while I was waiting for a reply. Here is the code with the changes.


async function RequestStreams() {

  got({

    url: "https://api.twitch.tv/helix/channels?broadcaster_id=44445592",

    method: "GET",

    headers: {

      'Content-Type': 'application/json',

      'Client-ID': TwitchClientID,

      'Authorization': `Bearer `+ accessToken

    },

    responseType: "json"

}).then(resp => {

  console.log("Ok", resp.body);

  if (resp.body.expires_in <= 3600) {

      twitch.makeClientCred();

  } else {

      // it"s ok

  }

}).catch(err => {

  console.log('Error Time!')

  console.error(err);

});

}

Still getting the same error though

Change

}).catch(err => {

  console.log('Error Time!')

  console.error(err);

});

To

}).catch(err => {

  console.log('Error Time!')

  console.error(err, err.response.body);

});

That should spit out the response body

Done.


HTTPError: Response code 401 (Unauthorized)
    at onResponse (D:\Twitch API Development\TwitchAppAnalytics\node_modules\got\dist\source\as-promise\index.js:124:28)
    at processTicksAndRejections (internal/process/task_queues.js:97:5) {
  code: undefined,
  timings: {
    start: 1592765404281,
    socket: 1592765404281,
    lookup: 1592765404294,
    connect: 1592765404305,
    secureConnect: 1592765404326,
    upload: 1592765404326,
    response: 1592765404475,
    end: 1592765404476,
    error: undefined,
    abort: undefined,
    phases: {
      wait: 0,
      dns: 13,
      tcp: 11,
      tls: 21,
      request: 0,
      firstByte: 149,
      download: 1,
      total: 195
    }
  }
} { error: 'Unauthorized', status: 401, message: 'Invalid OAuth token' }

Saying Invalid OAuth Token but I am Validating the OAuth Token and its coming back fine.
Posting my Validating Code below


async function requestValidate() {

request.post('https://id.twitch.tv/oauth2/token?client_id='+process.env.TWITCH_CLIENT_ID+'&client_secret='+process.env.TWITCH_SECRET+'&grant_type=client_credentials', function (error, response, body) {

    console.error('error:', error); // Print the error if one occurred

    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received

    console.log('body:', body); // Print the HTML for the Google homepage.

    console.log(body);

    const authJson = JSON.parse(body);

    const accessToken = authJson.access_token;

      got({

          url: "https://id.twitch.tv/oauth2/validate",

          method: "GET",

          headers: {

              Authorization: "OAuth " + accessToken

          },

          responseType: "json",

      }).then(resp => {

        console.log("Validated: ", resp.body);

        if (resp.body.expires_in <= 3600) {

            twitch.makeClientCred();

        } else {

            // it"s ok

        }

    }).then(stream => {

      RequestStreams()

    })

    .catch(err => {

        console.error(err);

        twitch.makeClientCred();

    });

    

});

}

Console:


https://id.twitch.tv/oauth2/token?client_id=REDACTED&client_secret=REDACTED&grant_type=client_credentials
Twitch auth sample listening on port 3000!
error: null
statusCode: 200
body: {"access_token":"REDACTED","expires_in":4783417,"token_type":"bearer"}

{"access_token":"REDACTED","expires_in":4783417,"token_type":"bearer"}

Validated:  {
  client_id: 'REDACTED',
  scopes: [],
  expires_in: 4783417
}

hmm can you put all your code up somewhere.

I have a feeling accessToken is blank in your call to streams.

Additionally you are mixing both requests and got. Which is “ok” just odd to use two libraries that do the same thing

Yeah, I found I was having issues with requests and Oauth2. Need to remove it at some point really.

Also Im storing my variables in a .env file as
TWITCH_CLIENT_ID=‘REDACTED’
TWITCH_SECRET=‘REDACTED’

Theres your problem.

You locked the access token to that function, it’s not available to other functions to use. So it’s undefined.

Ah, I thought I had checked that. Thanks for the help.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.