restauthorizationtwitch-api

How to retrieve the Twitch API bearer token


I'm not sure how to summarize this problem other than either some of the most passive aggressive or clueless docs I have ever scoured (and I've seen and written my fair share!) especially from a subsidiary of an ostensibly fortune 5 company

In any case: as an aspiring Twitch API user, I want to perform general server side requests of Twitch API resources (user/channel resources etc) and I need to provide a Bearer Token in an Authorization header.

Ok, easy enough you think? Oh you sweet summer child, the Twitch docs have incredibly detailed sections on the four different authorization flows you can venture to try to get this mysteriously hard to retrieve token (that is literally like 1 step in any other API)

Each of those flows have a fairly good step by step enumeration and how you need to first make sure you have a twitch application registered and the app's Client-Id and client Secret handy.

After that step, the closest you get is downloading the Twitch CLI, invoking the twitch token command and then passing in your Client-Id and client secret to get an expiring access token that can be passed in as the bearer, but what if:

  1. the twitch CLI won't install on my machine?
  2. I don't want to install the twitch CLI?
  3. I need to generate a new access token programmatically (which is like, the whole point of an API???) without bash scripting a CLI?

Solution

  • tl;dr, this took me way too much time, so I'm sharing with you because it's ridiculous this took so long:

    POST https://id.twitch.tv/oauth2/token?grant_type=client_credentials

    Headers "Content-Type":"application/x-www-form-urlencoded"

    Form body: (choose 'form' option in Insomnia or Postman)

    client_id <your app's client id>
    client_secret <your app's client secret>
    redirect_uri <your app's redirect uri (localhost is fine!)>
    code <your app's client secret (yes, again)
    

    Posting that worked for me, and returned this 200 OK and JSON response:

    {
      "access_token": "<relevant access token>",
      "expires_in": 5046783,
      "token_type": "bearer"
    }
    

    Although the Twitch docs liberally share plenty of other endpoints, for some reason I can only speculate on, they do not share explicitly and clearly share the endpoint for retrieving the endpoint for generating Twitch API bearer tokens.

    Fortunately, they do share their Twitch CLI's code on Github which we can investigate further.

    Within this codebase, we can see several urls assigned to variables and called in a nested if statement in the cmd go file.

    After chasing around the repo and some smooth brain keyboard bashing, I got the result I was looking for.

    I hope you find this useful and please don't write docs like this at your company!