Twitch をアイデンティティプロバイダーとして設定する
注釈:本資料はAI技術を用いて翻訳されています。
概要
このガイドは、認証されたTwitchデベロッパーがTwitchアカウントをAccelByte Gaming Services (AGS) に接続するのを支援することを目的としています。ここに記載されていないTwitchサービス内の追加機能を設定する必要がある場合があります。Twitchサービスの設定に関する完全な情報については、Twitchの担当者に連絡し、Twitchドキュメントを直接確認することをお勧めします。
このガイドは公開用であり、機密性のため限定的な情報が含まれています。まず完全な機密ガイドを参照することをお勧めします。機密ガイドのコピーをリクエストするには、AccelByteテクニカルプロデューサーにお問い合わせください。
目標
- AccelByte Game SDKを使用してゲームのTwitch認証方法を有効にする。
- AccelByte Player Portalを使用してパブリッシャーウェブサイトのTwitch認証方法を有効にする。
前提条件
ウェブログイン統合
- 認証されたTwitchアカウントとTwitchデベロッパーアクセスが必要です。
- 認証を設定し、権限を管理するためのAccelByte Admin Portalアカウント。
- Player PortalとLauncher用のパブリッシャーNamespace。
- Player Portal。
ウェブログイン統合は現在AGS Shared Cloudでは利用できず、AGS Private Cloudでのみサポートされています。
ゲーム内ログイン統合
- 認証されたTwitchアカウントとTwitchデベロッパーアクセスが必要です。
- 認証を設定し、権限を管理するためのAccelByte Admin Portalアカウント。
- ゲームNamespace。
- 最新バージョンのAccelByte Game SDKがインポートされたUnityまたはUnrealゲームプロジェクト。
- AGS Identity and Access Management (IAM) Clientsに関する知識。
Twitchアプリの設定
Twitch Developer Organizationsの設定(オプション)
Twitch Developer Organizationsを設定します。Registering and Managing Organizations Guideに従ってください。
Twitch 2FAの有効化
Twitchアカウントの2FAを有効にします。Setting up Two-Factor Authentication Guideに従ってください。
アプリケーションの登録
Twitch Developer Consoleでアプリケーションを登録します。Registering Your App Guideに従ってください。
Twitch Developer Consoleでの設定に問題がある場合は、カスタマーサポートに連絡してAccelByteからガイドを入手してください。
Twitchログイン方法の設定
ウェブログイン
次の手順に従って、プレイヤーポータルでTwitchログインを設定します。これにより、プレイヤーはTwitchアカウントを使用してプレイヤーポータルにサインインできるようになります。
-
AGS Admin portalで、パブリッシャーnamespaceに移動します。
-
サイドバーメニューで、Game Setup > 3rd Party Configuration > Auth & Account Linkingに移動します。
-
Login Methodsページで、+ Add Newボタンをクリックします。

-
ログイン方法オプションのリストから、Twitchを選択します。

-
Twitchアプリ認証情報でログイン設定を入力します。Client IDにtwitch clientIDを、Client Secretにtwitch client secretを入力し、Redirect URIにTwitchログインリダイレクトURI:
<BaseURL>/iam/v3/platforms/twitch/authenticateを入力します(BaseURLはドメインアドレス、例: https://development.accelbyte.io)。
-
詳細ページにリダイレクトされます。この時点でアクティベートするだけで使用できるようになります。

試してみる
パブリッシャーnamespaceでTwitchログイン方法を既に設定していることを確認してください。
-
Player Portalに移動し、Loginをクリックします。

-
Twitchをクリックします。アイコンが見つからない場合は、More login optionsをクリックしてLogin with Twitchをクリックできます。

-
Twitchアカウント認証情報でログインします。

現在、プレイヤーはTwitchアカウントを既存のAccelByteアカウントにリンクするか、新しいアカウントにリンクするよう求められます。AccelByteでは、プレイヤーがヘッドレスアカウントでPlayer Portalに直接ログインできるように、これを設定可能にする取り組みが進行中です。
ゲーム内ログイン
-
AGS Admin portalで、ゲームnamespaceに移動します。
-
サイドバーメニューで、Game Setup > 3rd Party Configuration > Auth & Account Linkingに移動します。
-
Login Methodsページで、+ Add Newボタンをクリックします。

-
ログイン方法オプションのリストから、Twitchを選択します。

-
Twitchアプリ認証情報でログイン設定を入力します。Client IDにtwitch clientIDを、Client Secretにtwitch client secretを入力し、Redirect URIにBaseURLドメインを入力します(BaseURLはドメインアドレス、例: https://development.accelbyte.io)。

-
詳細ページにリダイレクトされます。この時点でアクティベートするだけで使用できるようになります。

Twitch用のIAMクライアントの作成
IAMクライアントは、ターゲットプラットフォームでリリースしたいゲームクライアントの表現です。
特定のSDKプラットフォーム(Xbox、Steam、Playstationなど)のゲーム用のIAMクライアントを既に持っている場合は、新しいIAMクライアントを作成する必要はありません。Twitchはゲームを構築するプラットフォームではないため、既存のIAMクライアントを使用できます。IAMクライアントの詳細については、Manage Access control for applicationsの記事を参照してください。
ゲーム内ログイン統合
各ゲームエンジンの設定は異なります。利用可能なタブからゲームエンジンを選択してください。
- Unreal Engine手順
- Unity Engine手順
Unreal Engineゲーム内ログイン統合
Unreal準備と設定
依存関係の追加
まず、AccelbyteUe4Sdkという公開依存関係モジュールを追加する必要があります。この依存関係は、Unreal Engine内でAccelByte SDKプラグインを使用するためにプロジェクトを統合するために必要です。
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" });
}
<YourProject>.Target.csと<YourProjectEditor>.Target.cs内にAccelbyteUe4Sdkを追加します。
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" } );
}
Twitchログイン用のUnreal Engineプロジェクト設定
DefaultEngine.iniファイル内に、DefaultEngine.iniにAccelByte認証情報を追加してください。
[/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サンプルコード実装
次のステップでは、以下のサンプルコードを使用してゲームのTwitch認証方法を実装する方法を示します。
- BluePrintでWebBrowserアイテムをログインコンテナとして作成します。
- Login Twitch Urlをロードし、認証パラメータを追加します:
- redirect_uri: ログインが完了したときのRedirectURL。リダイレクトはゲームに戻るため、BaseURL(ApiClient->Settings->BaseUrl)で値を入力します。また、ホワイトリストに登録するために、Twitch developer portalのRedirect Uri設定にBaseUrl値を入力します。
- response_type: **"code"**で値を入力します。
- scope: 権限スコープで値を入力します。
スニペットで使用されるAccelByteOnlineSubsystemPtrを取得するには、このガイドに従ってください。
auto ApiClient = AccelByteOnlineSubsystemPtr->GetApiClient(TEXT("YOUR_KEY"));
auto UserApi = ApiClient->GetUserApi().Pin();
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://id.twitch.tv?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 = ApiClient->Settings->BaseUrl;
FString LoginCode = TEXT("");
if (Url.Contains(RedirectUri))
{
LoginCode = FGenericPlatformHttp::GetUrlParameter(Url, TEXT("code")).GetValue();
}
if (!LoginCode.IsEmpty())
{
UserApi->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)
}
}
Twitch認証のplatform_tokenはAuth/Login Codeです。
このサンプルコードをプロジェクトに追加した後、プロジェクトをコンパイルし、ビルドして実行します。以上です!
サンプルコードのテスト
以下に、コードが機能し、サンプルコードを使用してTwitchでログインできることを示すスクリーンショットを投稿します。

Unityゲーム内ログイン統合
TwitchをAccelByte SDKとサインインに統合して、プレイヤーがTwitch認証情報を使用してゲームにログインできるようにすることができます。
Unity準備と設定
AccelByte Gaming Services用のUnityプロジェクト設定
AccelByte SDKがプロジェクトで正しく実行される前に、AccelByte Admin Portalで以前に作成した値を入力し、以下の各ステップに従う必要があります:
- ゲームクライアント設定用にAccelByteSDKConfig.jsonという名前のファイルを作成します。
- AccelByteSDKConfig.jsonファイルをコピーし、Assets/ResourceディレクトリのUnityプロジェクトディレクトリに追加します。
- ゲームに基づいた情報を使用してAccelByteSDKConfig.jsonファイルに入力します。JSONファイルの例は次のとおりです:
{
"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>"
}
}
- AccelByteServerSDKConfig.jsonという名前のファイルを作成し、Assets/ResourceディレクトリのUnityプロジェクトディレクトリに追加します。
- ゲームサーバー設定として使用される以下のコードでAccelByteServerSDKConfig.jsonを更新します。JSONファイルの例は次のとおりです:
{
"Default": {
"Namespace": "<Your Game Namespace>",
"BaseUrl": "https://prod.gamingservices.accelbyte.io",
"RedirectUri": "http://127.0.0.1"
}
}
- AccelByteSDKOAuthConfig.jsonとAccelByteServerSDKOAuthConfig.jsonという名前の2つのファイルを作成します。これらのファイルの両方をAssets/ResourcesディレクトリのUnityプロジェクトディレクトリに追加します。これらのJSONファイルの両方の内容は次のようになります:
{
"Default": {
"ClientId": "<Your IAM Client ID>",
"ClientSecret": "<Your IAM Client Secret>"
}
}
Unityサンプルコード実装
次のステップでは、以下のサンプルコードを使用してゲームのTwitch認証方法を実装する方法を示します。
twitch apiを呼び出すためのカスタムsdkを作成する必要があります。以下は例です:
[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;
}
}
以下のコードは、GetAuthSessionTicketメソッドから取得した認証トークンによってサードパーティプラットフォームログインを処理するAccelByte SDKの一部であるLoginWithOtherPlatformを処理します。
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()}";
}
});
Twitch認証のplatform_tokenはAuth/Login Codeです。
Login Handlerスクリプトをプロジェクトに追加した後、プロジェクトをコンパイルできます。
サンプルコードのテスト
これで、プロジェクトをビルドして実行できます。以下に、コードが機能し、Twitchとテストアプリを使用してログインできることを示すスクリーンショットを投稿します。
