Set up Twitch as an identity provider
Overview
This guide is intended to help verified Twitch developers to connect Twitch Accounts to AccelByte Gaming Services (AGS). You may need to set up additional features within Twitch services which are not listed here. For full information about setting up Twitch services, we recommend contacting your Twitch representative and reviewing Twitch documentation directly.
This guide is intended for public use and contains limited information due to confidentiality. We recommend you refer to the full confidential guide first. Contact your AccelByte Technical Producer to request a copy of the guide.
Goals
- Enable the Twitch authentication method for your game with the AccelByte Game SDK.
- Enable the Twitch authentication method for your publisher website with the AccelByte Player Portal.
Prerequisites
Web Login Integration
- You must have an Verified Twitch Account and Developer Twitch Access.
- An AccelByte Admin Portal Account to set up authentication and manage permissions.
- A publisher Namespace for your Player Portal and Launcher.
- A Player Portal.
In-game login integration
- You must have an Verified Twitch Account and Developer Twitch Access.
- An AccelByte Admin Portal Account to set up authentication and manage permissions.
- A game Namespace.
- A Unity or Unreal game project with the latest version of the AccelByte Game SDK imported.
- Familiarity with AGS Identity and Access Management (IAM) Clients.
Setting up Twitch App
Set Up Twitch Developer Organizations (optional)
Set up Twitch Developer Organizations. Follow the Registering and Managing Organizations Guide
Enable Twitch 2FA
Enable 2FA for your Twitch Account. Follow the Setting up Two-Factor Authentication Guide
Register Application
Register Application on your Twitch Developer Console. Follow the Registering Your App Guide
Please contact Customer Support to get the guide from AccelByte if you have trouble setting up on Twitch Developer Console.
Set up Twitch login method
Web Login
Use the following steps to set up Twitch logins in the player portal. This will allow your players to sign in to your player portal using their Twitch accounts.
In the AGS Admin portal, go to your publisher namespace.
On the sidebar menu, go to Game Setup > 3rd Party Configuration > Auth & Account Linking.
On the Login Methods page, click on the + Add New button.
From the list of login method options, select Twitch.
Fill the login configuration with your Twitch App credentials. Fill Client ID with your twitch clientID, Client Secret with your twitch client secret and Fill Redirect URI with Your Twitch Login Redirect URI:
<BaseURL\>/iam/v3/platforms/twitch/authenticate
(BaseURL is your domain address, e.g., https://development.accelbyte.io).You will redirect to the detail page, at this point you just need to activate it and it will able to be used.
Give it a try
Make sure you have already set up the Twitch login method in your publisher namespace.
Go to your Player Portal and click on Login.
Click on Twitch. If you can't find it icon, you can click More login options and click Login with Twitch.
Login with your Twitch account credential.
Currently, players will be asked to link their Twitch account with an existing AccelByte account or link it with a new account. There is an effort underway at AccelByte to make this configurable so that players can login to the Player Portal directly with a headless account.
In-game login
In the AGS Admin portal, go to your game namespace.
On the sidebar menu, go to Game Setup > 3rd Party Configuration > Auth & Account Linking.
On the Login Methods page, click on the + Add New button.
From the list of login method options, select Twitch.
Fill the login configuration with your Twitch App credentials. Fill Client ID with your twitch clientID, Client Secret with your twitch client secret and Fill Redirect URI with Your BaseURL Domain (BaseURL is your domain address, e.g., https://development.accelbyte.io).
You will redirect to the detail page, at this point you just need to activate it and it will able to be used.
Create an IAM client for Twitch
An IAM client is a representation of the game client that you want to release on your target platform.
If you already have an IAM Client for your game on a specific SDK Platform (e.g., Xbox, Steam, or Playstation), you don't have to create a new IAM Client. Since Twitch is not a platform on which to build games, you can use an existing IAM Client. To learn more about IAM Clients, see the Manage Access control for applications article.
In-game login integration
The setup for each game engine is different. Please choose your game engine from the available tabs.
- Unreal Engine Instructions
- Unity Engine Instructions
Unreal Engine In-game login integration
Unreal Preparation and Configuration
Adding dependency
First you need to add public dependency modules called AccelbyteUe4Sdk, This dependencies needed for integrating your project to use the our AccelByte SDK Plugin within Unreal Engine.
public ABThirdPartyLogin(ReadOnlyTargetRules Target) : base(Target)
{
PCHUsage = PCHUsageMode.UseExplicitOrSharedPCHs;
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore" , "AccelByteUe4Sdk", "Slate", "SlateCore" });
PrivateDependencyModuleNames.AddRange(new string[] { "Json", "HTTP" });
}
Add AccelbyteUe4Sdk inside <YourProject>.Target.cs
and <YourProjectEditor>.Target.cs
public ABThirdPartyLoginTarget( TargetInfo Target) : base(Target)
{
Type = TargetType.Game;
DefaultBuildSettings = BuildSettingsVersion.V2;
ExtraModuleNames.AddRange( new string[] { "ABThirdPartyLogin", "AccelByteUe4Sdk" } );
}
public ABThirdPartyLoginEditorTarget( TargetInfo Target) : base(Target)
{
Type = TargetType.Editor;
DefaultBuildSettings = BuildSettingsVersion.V2;
ExtraModuleNames.AddRange( new string[] { "ABThirdPartyLogin", "AccelByteUe4Sdk" } );
}
Unreal Engine Project Setting for Twitch Login
Inside your DefaultEngine.ini file please Add AccelByte credential here on DefaultEngine.ini
[/Script/AccelByteUe4Sdk.AccelByteSettings]
ClientId=<Your Client_Id>
ClientSecret=<Your Client_Secret>
Namespace=<Your Namespace>
PublisherNamespace=<Your Publisher Namespace>
RedirectURI="http://127.0.0.1"
BaseUrl="https://prod.gamingservices.accelbyte.io"
IamServerUrl="https://prod.gamingservices.accelbyte.io/iam"
PlatformServerUrl="https://prod.gamingservices.accelbyte.io/platform"
Unreal Sample Code Implementation
Next step, we will show you how to implement the Twitch authentication method for your game with sample code below.
- Create WebBrowser item in BluePrint as a login container.
- Load Login Twitch Url and add auth params :
- redirect_uri: RedirectURL when login is done. Since redirection is back to the game fill value with BaseURL (FRegistry::Settings.BaseUrl). Also, put the BaseUrl value in the Redirect Uri config in the Twitch developer portal to whitelist.
- response_type: Put value with "code".
- scope: Put value with permission scope.
void UAccelByteAuth::TwitchLogin()
{
FString TwitchClientId;
GConfig->GetString(TEXT("TwitchClientId"), TwitchClientId, GEngineIni);
FString RedirectUri = TEXT("YOUR_TWITCH_REDIRECTURI");
FString Scope = TEXT("user:read:email");
FString Url = FString::Printf(TEXT("https://your_domain?client_id=%s&redirect_uri=%s&response_type=%s&scope=%s"),
*FGenericPlatformHttp::UrlEncode(TwitchClientId),
*FGenericPlatformHttp::UrlEncode(RedirectUri),
TEXT("code"),
*FGenericPlatformHttp::UrlEncode(Scope));
WBrowser_LoginAuth->LoadURL(Url);
WBrowser_LoginAuth->OnUrlChanged.AddUniqueDynamic(this, &UAccelByteAuth::AccelByteLoginWithTwitch);
}
void UAccelByteAuth::AccelByteLoginWithTwitch(const FText& NewUrl)
{
FString Url = NewUrl.ToString();
FString RedirectUri = FRegistry::Settings.BaseUrl;
FString LoginCode = TEXT("");
if (Url.Contains(RedirectUri))
{
LoginCode = FGenericPlatformHttp::GetUrlParameter(Url, TEXT("code")).GetValue();
}
if (!LoginCode.IsEmpty())
{
FRegistry::User.LoginWithOtherPlatform(AccelByte.Models.PlatformType.Twitch, LoginCode, FVoidHandler::CreateWeakLambda(this, [this]()
{
// Handle Success Login
}),
FCustomErrorHandler::CreateWeakLambda(this, [](int32 ErrorCode, const FString& ErrorMessage, const FJsonObject& ErrorJson)
{
// Handle Error Login
}));
// Close Login Page (Hide WebBrowser)
}
}
platform_token
for Twitch Authentication is Auth/Login Code
After adding this sample code to your project, compile your project, then build and run your project. That's it!
Sample Code Testing
Below we post a screenshot demonstrating that the code works and we are able to login using Twitch with the sample code.
Unity In-game login integration
You can integrate your Twitch to sign-in with AccelByte SDK so that your players can log in to games using Twitch credentials.
Unity Preparation and Configuration
Unity Project Setting for AccelByte Gaming Services
Before the AccelByte SDK can run properly in your project, you need to fill in the values that you created previously in the AccelByte Admin Portal and follow each step below:
- Create a file for Game Client configuration named AccelByteSDKConfig.json.
- Copy the AccelByteSDKConfig.json file and add it to your Unity project directory in the Assets/Resource directory.
- Fill in the AccelByteSDKConfig.json file using the information based on your game. Here is an example of the JSON file:
{
"Default": {
"Namespace": "<Your Game Namespace>",
"UsePlayerPrefs": true,//It will use Player Preferences
"EnableDebugLog": true,//Enable Debug Logging
"DebugLogFilter": "Log",//Type of Debug Log
"BaseUrl": "https://prod.gamingservices.accelbyte.io",
"RedirectUri": "http://127.0.0.1",
"AppId": "<Your AppId>",
"PublisherNamespace": "<Your Publisher Namespace>"
}
}
- Create a file called AccelByteServerSDKConfig.json and add it to your Unity project directory in the Assets/Resource directory.
- Update the AccelByteServerSDKConfig.json with the code below that will be used as the Game Server configuration. Here is an example of the JSON file:
{
"Default": {
"Namespace": "<Your Game Namespace>",
"BaseUrl": "https://prod.gamingservices.accelbyte.io",
"RedirectUri": "http://127.0.0.1"
}
}
- Create two files named AccelByteSDKOAuthConfig.json and AccelByteServerSDKOAuthConfig.json. Add both of these files to your unity project directory in the Assets/Resources directory. The contents of both these JSON files should be as follows:
{
"Default": {
"ClientId": "<Your IAM Client ID>",
"ClientSecret": "<Your IAM Client Secret>"
}
}
Unity Sample Code Implementation
Next step, we will show you how to implement the Twitch authentication method for your game with sample code below.
You need to create custom sdk to call twitch api, here's the example:
[SerializeField] Button TwitchLoginButton;
[SerializeField] Text LoginStatus;
[SerializeField] private string clientId = "YOUR_TWITCH_CLIENTID";
[SerializeField] private string clientSecret = "YOUR_TWITCH_CLIENTSECRET";
[SerializeField] private string redirectUri = "YOUR_TWITCH_REDIRECTURI";
[SerializeField] private string authorizationUrl = "https://id.twitch.tv/oauth2/authorize";
[SerializeField] private string tokenUrl = "https://id.twitch.tv/oauth2/token";
string[] scopes = { "user:read:email" };
// AccelByte's Multi Registry references
private ApiClient apiClient;
private User user;
};
private const string authUrl =
private async void OnLoginClick()
{
TwitchLoginButton.interactable = false;
LoginStatus.text = "Logging in...";
string scopeStr = string.Join("%20", scopes);
string url = $"{authorizationUrl}?client_id={clientId}&redirect_uri={redirectUri}&response_type=code&scope={scopeStr}";
// Open the URL in the default browser
Application.OpenURL(url);
// Wait for the authorization code
string authCode = await GetAuthorizationCode();
Debug.Log($"Twitch auth code: {authCode}");
LoginStatus.text = "Auth Code Received Login In";
}
private async Task<string> GetAuthorizationCode()
{
string authCode = "";
bool receivedAuthCode = false;
// Wait for the user to complete the authentication process and receive the authorization code
float elapsedTime = 0;
float timeout = 10f; // Maximum time to wait for the user to complete the authentication process (in seconds)
while (!receivedAuthCode && elapsedTime < timeout)
{
authCode = await ListenForAuthorizationCode(redirectUri);
elapsedTime += 1f;
// Check if the authorization code has been received
if (!string.IsNullOrEmpty(authCode))
{
receivedAuthCode = true;
}
}
return authCode;
}
private async Task<string> ListenForAuthorizationCode(string redirectUri)
{
string authCode = "";
// Create a HttpListener instance to listen on the redirect URI
var listener = new HttpListener();
listener.Prefixes.Add(redirectUri);
listener.Start();
// Wait for a request to be received on the HttpListener
var context = await listener.GetContextAsync();
// Extract the authorization code from the request URI
var requestUri = context.Request.Url;
authCode = HttpUtility.ParseQueryString(requestUri.Query).Get("code");
// Send a response to the request with an HTML page that displays the authorization code
var response = context.Response;
var responseString = $"<html><body><h1>Authorization Code: {authCode}</h1></body></html>";
var buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
var output = response.OutputStream;
await output.WriteAsync(buffer, 0, buffer.Length);
// Close the HttpListener and return the authorization code
listener.Close();
return authCode;
}
}
This code below will handle LoginWithOtherPlatform which is the part of AccelByte SDK that handles third-party platform login by auth token obtained from the GetAuthSessionTicket method.
var apiClient = AccelByteSDK.GetClientRegistry().GetApi();
var user = apiClient.GetUser();
Result < TokenData, OAuthError > loginResult = null;
user.LoginWithOtherPlatform(PlatformType.Twitch, AuthToken, (Result < TokenData, OAuthError > loginResult) => {
if (loginResult.IsError) {
//If we error, grab the Error Error and Description to print in the Log
Debug.Log($ "Login failed : {loginResult.Error.error} Description : {loginResult.Error.error_description}");
//Set the Status Text to display the Error if there is any
LoginStatus.text = $ "Login failed : {loginResult.Error.error} Description : {loginResult.Error.error_description}";
} else {
Debug.Log($ "Login successful : {loginResult.Value}");
LoginStatus.text = $ "Success Login Twitch:{loginResult.Value.ToJsonString()}";
}
});
platform_token
for Twitch Authentication is Auth/Login Code.
After adding the Login Handler Script into your project, you can compile your project.
Sample Code Testing
Now, you can build and run your project. Below we post a screenshot demonstrating that the code works and we are able to login using Twitch and our test app.