Nightbot API 400 - badly written POST-request?

Hi there!

I am trying to make POST request to Nightbot after getting my auth-code, but getting a 400, not sure what I have done wrong and am wondering if someone could take a look at my code. I am fairly sure I have written it correctly:

[details=Summary]$.ajax({ url: 'https://api.nightbot.tv/oauth2/token', type: 'POST', dataType: 'json', data: { 'client_id':'IDfromNightbot', 'client_secret':'SecretFromNightbot', 'grant_type':'authorization_code', 'redirect_uri':'http://127.0.0.1:10100', 'code':'AuthCodeFromLastStep' }, success: function (datad) { $('#summary').html(datad); }[/details]

First and foremost, you should never make OAuth2 token calls containing a secret from client-side code. Your client secret is a secret, and must be kept on a backend server and not shared with clients.

Additionally, if you’re just making an integration for yourself to use, you can skip the authorization code and authenticate with client credentials instead:

POST https://api.nightbot.tv/oauth2/token
    grant_type=client_credentials&
    client_id=CLIENT_ID&
    client_secret=CLIENT_SECRET

If you’re building an integration for others to use, you want to exchange the code for a token using your secret on a backend server. The problem with your code sample is you’re probably posting JSON, whereas the endpoint (as per the OAuth2 RFC) is accepting urlencoded data as the body

1 Like

Managed to get my POST working now, but sadly not with AJAX. You were right about URL-encoding, I was using Json… What is wrong now I am not sure about. I changed my POST to the following but still getting a 404:

[details=Summary]$.ajax({ url: 'https://api.nightbot.tv/oauth2/token', type: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, data: { 'client_id':'XXX', 'client_secret':'YYY', 'grant_type':'client_credentials' }, success: function (datad) { $('#summary').html(datad); }, error: function(){ alert("Cannot get data"); } });[/details]

You should not be using AJAX for making tokens… As per my previous reply:

First and foremost, you should never make OAuth2 token calls containing a secret from client-side code. Your client secret is a secret, and must be kept on a backend server and not shared with clients.