Twitch Authentication for Unity
A Unity Asset by Firesplash Entertainment
Best Practice Guide

If you want to let the user log in with twitch and always have a valid token available in your game, without requiring the user to re-login after every game restart, this is the best practice guide to set up your game!

In this short guide, we will go through the most important steps of creating a game login scene. In the end we will introduce a method how you can access the valid twitch token on demand form any other script, for example to use the helix API.

This sample is included completely in the asset's Examples folder. Only steps 2 and 3 have to be taken using this sample.

Preparation

Step 1: Create the Authentication Manager

Object setup

We assume, that you have already created a simple UI contianing a status text view and two buttons for login/logout. The buttons are not interactable by default.

First of all you should create a new GameObject in your hierarchy. If you already have a GameObject that is set to DontDestroyOnLoad and which is available all the time (Could be a Game Manager for example), you can re-use that. For our BP Walkthrough we will create a GameObject right under the root, called AuthenticationManager.

Authentication Manager Script

We also create a new Script to this object, calling it AuthenticationManager (just as the object). This script is our game code, it will access the asset and do all the authentication stuff for us. This is the basic skeleton:

public class AuthenticationManager : MonoBehaviour
{
public TwitchAuthenticationHelper twitchAuth;
public Text lblLoginstatus;
public Button btnLogin, btnLogout;
bool areWeAwaitingAuthentication = true;
}

Assign your UI references right now.

Additionally we add our TwitchAuthenticationHelper script (from the asset) as a new component to this object and then drag and drop its reference into the Authentication Manager's "Twitch Auth" field.

Set the "Used Authentication Flow" to "Server Assisted Authorization Code Flow" and enable "Auto Refresh". The inspector should now look like that:

Make sure that the "Callback Server Port" setting says 51234 in the inspector (change it to this value).

Step 2: Creating an application on twitch

Please note: This is an important step! You also need to do this to try out our delivered example!

First, go to the Twitch Developer Console and log in there. near the middle of your screen, you should now see an "Applications" tab. Open it and click the button to register a new application.

Fill in the form and enter "http://localhost:51234" as redirect url. You can chose any other port, but it must match the setting in the inspector

After clicking the save button, you will be dropped back to the list. Click the "Manage" button next to your just created application and take a note of the Client-ID field (you will need it again later). Additionally, copy the Client-ID into the Inspector of the Twitch Authentication Helper (field Client ID).

Now click the "New Secret" button in the developer console and take anote of the generated secret for later use.

Step 3: Setting up the server side script

This is likely the most complicated part of this guide.

In our asset files, you can find a file called "TwitchAuthServer.php" - You should copy this file, edit the configuration block as described (also add a parole) and upload it to your server / webspace.

Now enter the full URL to this file into the inspector (field "Assistant Script URL"). Unfold "Advanced Configuration Options" and enter the Parole value. Hint: To make sure, you got the right URL, open it in a browser - it should say Game's request did not match configuration. Please check Unique ID configuration.

See also: Configuring Server Assisted Flow

Coding a simple Authentication Manager

You will likely already have in mind how you want to use this asset but for this guide, we will code a simple "login" procedure returngin a token that is capable of reading and writing into the twitch chat. This is a variant you can use to create an application for a streamer, like a chatbot based game. You can of course also simply use this asset to get a token on demand for an API call etc.

Step 4: Bringing our buttons to life

First of all, we will create the button callbacks and add calls to the Twitch Authentication Helper. For the LogIn-Button:

public void LogIn()
{
areWeAwaitingAuthentication = true;
btnLogin.interactable = false;
AuthenticationRequest authRequest = new AuthenticationRequest(false, AuthenticationRequest.ScopeSet.ChatReadWrite);
twitchAuth.Authenticate(authRequest);
}

Link this to the LogIn-Button using the inspector. This call will disable the login button and create a request containing one of our predefined ScopeSets for a token capable to read/write to the twitch chat on behalf of the logged in user. Then it reuests the helper to start the interactive authentication procedure.

See also
Firesplash.UnityAssets.TwitchAuthentication.AuthenticationRequest
Firesplash.UnityAssets.TwitchAuthentication.AuthenticationRequest.ScopeSet
Firesplash.UnityAssets.TwitchAuthentication.TwitchAuthenticationHelper.Authenticate

And this is for the LogOut-Button:

public void LogOut()
{
btnLogout.interactable = false;
btnLogin.interactable = true;
twitchAuth.ResetAuthentication();
lblLoginstatus.text = "You have been logged out";
}

Link this one to the LogOut-Button. It will clear the existing authentication and reenable the login button.

Right now nothing will happen after authenticating, so we need to proceed to the last step, which contains the actual work:

Step 5: Creating the callback

We will register our authentication callback on "Start". It is important to know that any authentication results in a callback being fired, no matter it it was interactive or a refresh and no matter if it was requested using Authenticate(...) or if it was an automatic refresh.

There are options to add a one time callback to Authenticate but this should not be used. Instead your script should be capable of receiving the said callback at any time and handling it correctly.

To achieve this, we have created the private property "areWeAwaitingAuthentication" to remember if we are currently awaiting an authentication (interactively). We will set this boolean to true when we call Authenticate() and back false after we received the callback resulting from this action. This boolean is also set to true initially because if we were logged in before, the AutoRefresh feature will take the last login's refresh token (on Start with a delay of one frame to make sure all scripts are initialized) and log the user in without interaction.

Now let's create our Start() method:

void Start()
{
DontDestroyOnLoad(this.gameObject);
twitchAuth.OnAuthenticationFinished.AddListener((result) => {
if (result == null)
{
//The user failed to complete an interactive login in time. (Timeout)
//At this point you might want to show an error dialog. Null always means user timeout.
btnLogin.interactable = true;
}
else if (areWeAwaitingAuthentication)
{
//we are waiting for authentication, so if it is not successful, we should show an error
if (result.isSuccessful)
{
areWeAwaitingAuthentication = false;
btnLogin.interactable = false;
btnLogout.interactable = true;
lblLoginstatus.text = "Logged in as: " + result.accessTokenMetadata.login;
}
else if (result.error.Equals("no_refresh_token"))
{
//This means that the user was never logged in, so the automatic login was not possible
btnLogin.interactable = true;
lblLoginstatus.text = "You are not logged in";
}
else
{
btnLogin.interactable = true;
lblLoginstatus.text = "Login was not successful: " + result.errorDescription;
}
}
});
}

Testing

You can now run the example and you should see an active login button a few moments after the game starts.

After clicking the login button, the browser should open and you should be presented with a twitch login/authorization request.

When you authorized the request, you will be directed to a simple HTML page telling you to close the browser window.

Back in the game, you should already be logged in or this action should finish within a few moments. This delay is caused by active communicaiton with your server script and the twitch servers.

After the login completed successfully, you can now stop the game (without logging out) and when you restart it, you will be automatically logged in.

After clicking the logout button, you will be logged out again and no auto login will take place until you log in again.

Thinking further

  • You could create an overlay while awaiting the callbacks to visually indicate the game is working
  • One might want to switch scenes after logging in. To get a token in the next scene, we have set the manager to not destroy on load. Get a reference (for example using FindObjectOfType<TwitchAuthenticationHelper>()) and access the token using some code like this:
    if (twitchAuth.LastAuthenticationResult != null && twitchAuth.LastAuthenticationResult.isSuccessful)
    {
    string token = twitchAuth.LastAuthenticationResult.accessToken;
    }