How to pass authorization token to another AJAX function?

Hello,

I’m in the process of changing the way my website gets Twitch data from API calls where I was using PHP and I need to use AJAX to get them. I’m able to get the authentication barear token but I’m having problems passing the token to another AJAX function that gets API data of a video.

Any ideas on what I’m doing wrong?

$.ajax({
type: “GET”,
url: “https://id.twitch.tv/oauth2/token?client_id=xxx&client_secret=xxx&grant_type=client_credentials”,
header: {
“Content-Type”:“application/x-www-form-urlencoded”
},
success: function (data) {
var a = JSON.parse(JSON.stringify(data.access_token)); // This line has the token
$.ajax({
type: “post”,
url: “https://api.twitch.tv/helix/videos?id=1493894959”,
header: {
'Authorization: Bearer ’ + a,
'Client-Id: ’ + ‘xxx’,
},
success: function (data) {
$(".text").text(JSON.parse(JSON.stringify(data.items[0].snippet.description)));
}.
dataType: ‘JSON’,
});
},
dataType: ‘JSON’,
});
})

Asssuming Ajax is being used in the front end. And you are trying to remove the server/PHP part

NEVER DO THIS YOU ARE LEAKING YOUR CLIENT SECRET AND GENERATED TOKEN

Since you have PHP your front end should be calling PHP and PHP should be generating/reusing a token and calling the API and returning the result.

If you want to be pure frontend with no server then you need to use implicit auth and ask the user to login to provide a token.

Otherwise someone can steal your ClientID and Secret and abuse them

Thats why all my code examples of things use implict auth, as I only tell you my clientID (which is public) Barry's Live/Testable Twitch examples

So if you are intending to remove PHP/server then you need to use implict auth not client credentials/app access.

Client Creds is for server to server calls and it seems like you are trying to remove the server from what you are doing.

TLDR: You are doing it wrong.

I got it work!

First of all, this is a WordPress site and this is all in the backend, nothing is publicly exposed. All it does it store data into fields and then displays them.

Here’s what I got working:

$.ajax({
type: “POST”,
url: “https://id.twitch.tv/oauth2/token?client_id=<?php echo $client_ID;?>&client_secret=<?php echo $client_secret;?>&grant_type=client_credentials”,
header: {
“Content-Type”:“application/x-www-form-urlencoded”
},
success: function (data) { // authentication token
$.ajax({
type: “GET”,
url: “https://api.twitch.tv/helix/videos?id=1493894959”, // Video ID from URL
headers: { // this was giving me problems
“Client-ID”: <?php echo $client_ID;?>
“Authorization”: "Bearer " + JSON.parse(JSON.stringify(data.access_token)) // token from eariler AJAX
},
success: function (data) {
$(’.text’).text(JSON.stringify(data)); // show output
},
dataType: ‘JSON’,
});
},
dataType: ‘JSON’,
});

Thanks for the help!

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