OAuth 400 Bad Request - But only the second time

Using the OAuth authorization code flow.

  • Game prompt the authorization page.
  • User agrees.
  • Redirect to our backend that stores the authorization code
  • Game calls for a status update from the backend
  • Backend requests OAuth token using Client ID, Secret and stored authorization code of that specific user
  • Token is used to retrieved User and Stream data
  • Parsed data is sent to the game

This works. However, if the user close the game or we reboot our backend, we get “400 Bad Request” on the “Request OAuth token” step.

If we restart the process from the beginning, and retrieved a new authorization code, everything works.

Is there an issue to requesting again an OAuth token before it’s expired? What to do if the token is lost (user gone, backend restarted)?

The message attached is “Invalid authorization code”, does a user really need to re-authorize a game everytime an OAuth token is requested?

The authorization code is one time use, so you shouldn’t be storing it at all but instead using it immediately when the user redirects to your backend.

Once your server exchanges the code it’ll get not just an Access Token, but a Refresh Token too, both of which should be stored so that the access token can be used for any API requests, and the refresh token used to generate a new access token and refresh token pair when the current token expires https://dev.twitch.tv/docs/authentication#refreshing-access-tokens

As long as the user hasn’t disconnect their Twitch account from your app, you’ll be able to use the refresh process whenever you need new tokens and not need the user to go through the process again.

Thanks!

Just to be clear, you says both Access and Refresh Tokens should be stored… But from reading the refresh page, only the Refresh Token is passed back to refresh the Access Token. What’s the reason for long-term storing the Access Token?

And I see the Refresh Token is passed back… I assume it also changes anytime we refresh the Access Token?

The reason for storing them both is so that even if you don’t need the access token to make an API request you can still use it to verify the user is still connected to your app, and if they have chosen to disconnect from your app you can use that to remove any data you have stored about the user from your systems.

The refresh token given after a refresh doesn’t always change, sometimes you get the same one back that you just used but some times you get a new one, so it’s always best to replace whatever previous tokens you had with the new ones you get given.