Provide a Facebook sign-in option to enable players to authenticate using their Facebook accounts in your game.
Read time 4 minutesLast updated 15 hours ago
Minimum SDK version: 2.0.0
This article guides you through the following scenarios in setting up authentication for players in your game with a Facebook account:- Set up a Facebook account sign-in
- Sign in a returning user or create new user.
- Updating a user from an anonymous sign-in to a platform sign-in via a Facebook account.
Set up a Facebook account sign-in
- Set up and install the Facebook SDK following Facebook’s getting started documentation.
-
Add Facebook as an Id Provider for Unity Authentication:
- In the Unity Editor menu, go to Edit > Project Settings…, then select Services > Authentication from the navigation menu.
- Set ID Providers to Facebook, then click Add.
- Enter the app ID (found in step 1) in the App ID text field.
- Enter the app secret in the App Secret text field, then click Save.
- Implement the Facebook login using this sample code.
using System.Collections.Generic;using UnityEngine;// Other needed dependenciesusing Facebook.Unity;public class FacebookExampleScript : MonoBehaviour{ public string Token; public string Error; // Awake function from Unity's MonoBehaviour void Awake() { if (!FB.IsInitialized) { // Initialize the Facebook SDK FB.Init(InitCallback, OnHideUnity); } else { // Already initialized, signal an app activation App Event FB.ActivateApp(); } } void InitCallback() { if (FB.IsInitialized) { // Signal an app activation App Event FB.ActivateApp(); // Continue with Facebook SDK } else { Debug.Log("Failed to Initialize the Facebook SDK"); } } void OnHideUnity(bool isGameShown) { if (!isGameShown) { // Pause the game - we will need to hide Time.timeScale = 0; } else { // Resume the game - we're getting focus again Time.timeScale = 1; } } public void Login() { // Define the permissions var perms = new List<string>() { "public_profile", "email" }; FB.LogInWithReadPermissions(perms, result => { if (FB.IsLoggedIn) { Token = AccessToken.CurrentAccessToken.TokenString; Debug.Log($"Facebook Login token: {Token}"); } else { Error = "User cancelled login"; Debug.Log("[Facebook Login] User cancelled login"); } }); }}
Sign in a returning player or create new player
You can use theSignInWithFacebookAsync- Create a new Unity Authentication player with the Facebook credentials.
- Sign in an existing player using the Facebook credentials.
SignInWithFacebookAsyncSignInWithFacebookAsyncSignInWithFacebookAsyncasync Task SignInWithFacebookAsync(string token){ try { await AuthenticationService.Instance.SignInWithFacebookAsync(token); Debug.Log("SignIn is successful."); } catch (AuthenticationException ex) { // Compare error code to AuthenticationErrorCodes // Notify the player with the proper error message Debug.LogException(ex); } catch (RequestFailedException ex) { // Compare error code to CommonErrorCodes // Notify the player with the proper error message Debug.LogException(ex); }}
Update a player from anonymous to a Facebook account
After you’ve set up anonymous authentication, if the player wants to upgrade from being anonymous to creating a Facebook account and sign in using Facebook, the game should prompt the player to trigger the Facebook login and get the access token from Facebook. Then, call theLinkWithFacebookAsync- Sign into the cached player's account using .
SignInAnonymouslyAsync - Link the cached player's account to the Facebook account with .
LinkWithFacebookAsync
When the player triggers the Facebook login by signing in or by creating a new player profile, and you have received the Facebook access token, call the following API to authenticate the player.async Task LinkWithFacebookAsync(string token){ try { await AuthenticationService.Instance.LinkWithFacebookAsync(token); Debug.Log("Link is successful."); } catch (AuthenticationException ex) when (ex.ErrorCode == AuthenticationErrorCodes.AccountAlreadyLinked) { // Prompt the player with an error message. Debug.LogError("This user is already linked with another account. Log in instead."); } catch (AuthenticationException ex) { // Compare error code to AuthenticationErrorCodes // Notify the player with the proper error message Debug.LogException(ex); } catch (RequestFailedException ex) { // Compare error code to CommonErrorCodes // Notify the player with the proper error message Debug.LogException(ex); }}
async Task SignInWithFacebookAsync(string token){ try { await AuthenticationService.Instance.SignInWithFacebookAsync(token); Debug.Log("SignIn is successful."); } catch (AuthenticationException ex) { // Compare error code to AuthenticationErrorCodes // Notify the player with the proper error message Debug.LogException(ex); } catch (RequestFailedException ex) { // Compare error code to CommonErrorCodes // Notify the player with the proper error message Debug.LogException(ex); }}
Implement a Facebook sign-in authentication
When the player triggers the Facebook login to login or create a new player, and you have received the Facebook access token, call the following API to sign-in the player:SignInWithFacebookAsync(string accessToken)Unlink Facebook account
Use theUnlinkFacebookAsyncasync Task UnlinkFacebookAsync(){ try { await AuthenticationService.Instance.UnlinkFacebookAsync(); Debug.Log("Unlink is successful."); } catch (AuthenticationException ex) { // Compare error code to AuthenticationErrorCodes // Notify the player with the proper error message Debug.LogException(ex); } catch (RequestFailedException ex) { // Compare error code to CommonErrorCodes // Notify the player with the proper error message Debug.LogException(ex); }}
Handle Facebook Limited Login on iOS devices
iOS 14 and later requires publishers to obtain permission to track the user's device across applications. This device setting is called App Tracking Transparency, or ATT. Please see Apple's documentation for more details. Without explicit consent, the Facebook SDK will default to the Facebook Limited Login flow. This provides a slightly different token, but it can still be used by Unity Authentication to associate a player. To help with this integration, Unity provides an optional iOS support package which supports requesting consent and querying the consent status. It can be found in the Unity editor Package Manager ascom.unity.ads.ios-supportAccessTokenAuthenticationTokenAccessTokenAuthenticationTokenusing System;using UnityEngine;using Unity.Services.Core;using Unity.Services.Authentication;// Other needed dependencies, including the iOS support packageusing Facebook.Unity;using Unity.Advertisement.IosSupport;public class FacebookExampleScriptWithIosAttHandling : MonoBehaviour{ async void Awake() { // This will prompt the player to consent to tracking when the app is first launched. // Only include this line here if it is not otherwise requested already. ATTrackingStatusBinding.RequestAuthorizationTracking(); // Initialize Unity services await UnityServices.InitializeAsync(); Debug.Log($"Unity services initialization: {UnityServices.State}"); if (!FB.IsInitialized) { // Initialize the Facebook SDK FB.Init(FbInitCallback, OnHideUnity); } else { // Already initialized, signal an activation App Event FB.ActivateApp(); } } void FbInitCallback() { if (FB.IsInitialized) { // Signal an app activation App Event FB.ActivateApp(); // Continue with Facebook SDK } else { Debug.Log("Failed to Initialize the Facebook SDK"); } } void OnHideUnity(bool isGameShown) { // Pause or resume the game depending on focus Time.timeScale = isGameShown ? 1 : 0; } // Call this from a button or similar public void LoginWithAttHandling() { FB.LogInWithReadPermissions(null, result => { if (FB.IsLoggedIn) { // Check ATT status to determine which token to use. // The states include AUTHORIZED, RESTRICTED, NOT_DETERMINED, and DENIED. if (ATTrackingStatusBinding.GetAuthorizationTrackingStatus() == ATTrackingStatusBinding.AuthorizationTrackingStatus.AUTHORIZED) { Debug.Log("[Facebook Login] Using standard access token"); SignInWithFacebookAsync(AccessToken.CurrentAccessToken.TokenString); } else { Debug.Log("[Facebook Login] Using Limited Login authentication token"); SignInWithFacebookAsync(result.AuthenticationToken.TokenString); } } else { Debug.Log("[Facebook Login] User cancelled login from within Facebook flow"); } }); } async void SignInWithFacebookAsync(string token) { try { await AuthenticationService.Instance.SignInWithFacebookAsync(token); Debug.Log("Unity SignIn is successful."); } catch (Exception ex) { Debug.LogException(ex); } }}