Authentication with Unity SDK
Quick Reference
This topic is specific to the AccelByte Gaming Services (AGS) Shared Cloud tier.
References
using AccelByte.Api;
using AccelByte.Core;
using AccelByte.Models;
Login
User user = AccelByteSDK.GetClientRegistry().GetApi().GetUser();
AccelByte.Core.ResultCallback<TokenData, OAuthError> loginCallback = loginResult =>
{
if (loginResult.IsError)
{
Debug.Log("Login failed");
// some actions
}
else
{
Debug.Log("Login successful");
// some actions
}
};
user.LoginWithUsernameV3(username, password, loginCallback);
Check if a player is logged in
AccelByteSDK.GetClientRegistry().GetApi().GetUser().Session.IsValid();
Quickstart Guide
In this section, you will learn how to log in and connect to the IAM Services.
Create a script called
LoginHandler.cs
and add the following AccelByte libraries to the top of the script:using AccelByte.Api;
using AccelByte.Models;
using AccelByte.Core;Set up the Login logic using the Username and Password method. In the script, add the following:
// Function called to Login by email to AccelByte's IAM services.
public void OnLoginClick(string username, string password)
{
// Grab a current User reference, even if it has not logged in yet.
User user = AccelByteSDK.GetClientRegistry().GetApi().GetUser();
// Create callback of login result
AccelByte.Core.ResultCallback<TokenData, OAuthError> loginCallback = loginResult =>
{
if (loginResult.IsError)
{
Debug.Log("Login failed");
// some actions
}
else
{
Debug.Log("Login successful");
// some actions
}
};
// Call the Login Function and supply a asynchronous callback to act based upon success or failure
user.LoginWithUsernameV3(username,password, loginCallback);
}Test your script by calling it from elsewhere in
MonoBehaviour
and supplying sample credentials.void Start()
{
OnLoginClick("user@example.net","SuperPassword");
}Attach your script to a new
GameObject
. In the example below, we have named this objectAccelByteHandler
. Test your object by pressing Play. If you have followed these steps correctly, you will see the message "Login successful" appear in your Console Log.Check whether the player is logged in by verifying that their session is valid.
AccelByteSDK.GetClientRegistry().GetApi().GetUser().Session.IsValid();
For testing purposes, place this code in the
Update
function of your script:void Update()
{
if (AccelByteSDK.GetClientRegistry().GetApi().GetUser().Session.IsValid())
{
Debug.Log("Logged in");
}
}When you press Play, you should see the player logged in with valid stored credentials. Once completed, remove this debug check from your script.
If you encounter a login failed message, check your login credentials or the API URLs supplied in the AccelByteSDKConfig.json
file.
If the error is related to .JSON reading, check the format of your AccelByteSDKConfig.json
file.
Congratulations! You have logged in.
Continue on for a step by step example of the UI and code implementation. Otherwise, you are now ready to move on to the Lobby service.
Step by step guide
UI Implementation
Create an empty object (such as
AccelByteHandler
in Step 4 of the Quickstart Guide above) to hold all of the script components of the IAM services implementation.For the Login Page, create a new panel or scene with the following objects:
- Username input field
- Password input field
- Login button
- Status text
Code Implementation
Add the following code to the top of your
LoginHandler.cs
class:using UnityEngine.UI;
Inside the class, add references to the UI components you just created:
[SerializeField]
Button loginButton;
[SerializeField]
Text statusText;
[SerializeField]
InputField usernameInputField;
[SerializeField]
InputField passwordInputField;
[SerializeField]
RectTransform loginPanel;In the
Start()
function, remove theOnLoginClick()
call and create two new functions,OnEnable()
andOnDisable()
.private void OnEnable()
{
// When we activate, set the text of the Login Status
// and add the Login Call to the button's listener
statusText.text = "Please Login";
loginButton.onClick.AddListener(()
=>
{
statusText.text = "Attempting Login";
OnLoginClick(usernameInputField.text, passwordInputField.text);
});
}
private void OnDisable()
{
// When we disable, clear all of the listeners from the login button
loginButton.onClick.RemoveAllListeners();
}Within the
OnLoginClick()
function, add the following basic login components and status text. This text will be visible to the player when they are logging in:public void OnLoginClick(string username, string password)
{
// Disable interaction with the login button so the player cannot spam click it and send multiple requests
loginButton.interactable = false;
statusText.text = "Logging in...";
...
ResultCallback<TokenData, OAuthError> loginCallback = loginResult =>
{
if (loginResult.IsError)
{
// If there is an error, grab the error code and message to print in the log
Debug.Log($"Login failed : {loginResult.Error.error}: {loginResult.Error.error_description}");
// Set the Status Text to display any errors
statusText.text = $"Login failed : {loginResult.Error.error}: {loginResult.Error.error_description}";
}
else
{
Debug.Log("Login successful");
loginPanel.gameObject.SetActive(false);
}
//Enable interaction with the button again
loginButton.interactable = true;
};
user.LoginWithUsernameV3(username, password, loginCallback);
...
}- Set the
loginButton
to be disabled while awaiting the result of the login request (so that the player cannot spam login requests). - Set the
statusText
to display a message (such as "Logging in...") to display to the player while the login request is processing. - Set the
statusText
to show the relevant error code and message should the login attempt fail. - Set the
loginPanel
to be disabled if the player logs in successfully. - Enable intractability on the
loginButton
after the login result is determined.
- Set the
Save and return to the Editor. In the
AccelByteHandler gameObject
, drag the corresponding objects into the five exposed variables in yourLoginHandler.cs
script.Save your scene, press Play, and type in your credentials. If your credentials are incorrect, an error message will appear in the log and status text.
If your credentials are correct, the scene will become blank as the LoginPanel
disappears.
Congratulations! You have fully implemented the Login, which is the gateway to all other services in AGS.
Proceed to the next section to learn how to implement the Lobby Service.
Full code for reference
LoginHandler.cs
using UnityEngine;
using AccelByte.Api;
using AccelByte.Models;
using AccelByte.Core;
using UnityEngine.UI;
public class LoginHandler : MonoBehaviour
{
[SerializeField]
Button loginButton;
[SerializeField]
Text statusText;
[SerializeField]
InputField usernameInputField;
[SerializeField]
InputField passwordInputField;
[SerializeField]
RectTransform loginPanel;
// Start is called before the first frame update
void Start()
{
}
private void OnEnable()
{
// When we activate, set the text of the Login Status
// and add the login call to the button's listener
statusText.text = "Please Login";
loginButton.onClick.AddListener(() =>
{
statusText.text = "Attempting Login";
OnLoginClick(usernameInputField.text, passwordInputField.text);
});
}
private void OnDisable()
{
// When we disable, clear all of the listeners from the Login button
loginButton.onClick.RemoveAllListeners();
}
/// <summary>
/// Function called to Login to AGS IAM services
/// </summary>
/// <param name="username">The Username (typically an email address) of the user</param>
/// <param name="password">The password of the user</param>
public void OnLoginClick(string username, string password)
{
// Disable Interaction with the Login button so the player cannot spam click it and send multiple requests
loginButton.interactable = false;
statusText.text = "Logging in...";
// Grab a reference to the current user, even though they have not been logged in yet
// This also acts as the initialization point for the AGS plug-in
User user = AccelByteSDK.GetClientRegistry().GetApi().GetUser();
// Calling the login function and supplying a callback to act upon based upon success or failure
// You will almost certainly want to extend this functionality further
// Note that this callback is asynchronous
ResultCallback<TokenData, OAuthError> loginCallback = loginResult =>
{
if (loginResult.IsError)
{
// If there is an error, grab the error code and message to print in the log
Debug.Log($"Login failed : {loginResult.Error.error}: {loginResult.Error.error_description}");
// Set the Status Text to display any errors
statusText.text = $"Login failed : {loginResult.Error.error}: {loginResult.Error.error_description}";
}
else
{
Debug.Log("Login successful");
loginPanel.gameObject.SetActive(false);
}
//Enable interaction with the button again
loginButton.interactable = true;
};
user.LoginWithUsernameV3(username, password, loginCallback);
}
}