Skip to content

Social Login (OAuth)

Allow users to authenticate using third-party OAuth providers like Google, Discord, Twitter, and more in your Unity game.

Methods

AuthenticateWithOAuth

Authenticate a user using OAuth providers like Google, Discord, Twitter, etc.

Method Signature:
public async UniTask<bool> AuthenticateWithOAuth(OAuthInitRequest request)
Parameters:
  • OAuthInitRequest request - OAuth authentication request
Returns:
  • UniTask<bool> - True if authentication was successful, false if cancelled
OAuthInitRequest Structure:
public class OAuthInitRequest
{
    public OAuthProvider Provider { get; set; }
    public bool UsePooling { get; set; }
    public OAuthInitRequestOptions Options { get; set; }
}
 
public enum OAuthProvider
{
    GOOGLE,
    DISCORD, 
    TWITTER,
    FACEBOOK,
    EPIC,
    OIDC,
    APPLE  // Available on iOS
}
 
public class OAuthInitRequestOptions
{
    public string RedirectTo { get; set; }  // Custom URL scheme for mobile
}

InitOAuth

Initialize OAuth authentication and get the authorization URL.

Method Signature:
public async UniTask<InitAuthResponse> InitOAuth(OAuthInitRequest request)
Parameters:
  • OAuthInitRequest request - OAuth initialization request
Returns:
  • UniTask<InitAuthResponse> - Contains the authorization URL
InitAuthResponse Structure:
public class InitAuthResponse
{
    public string Url { get; set; }        // Authorization URL
    public string State { get; set; }      // OAuth state parameter
}

GetUser

Get the currently authenticated user information.

Method Signature:
public async UniTask<AuthPlayerResponse> GetUser()
Parameters:
  • None
Returns:
  • UniTask<AuthPlayerResponse> - Current user information

Examples

using System;
using UnityEngine;
using Cysharp.Threading.Tasks;
using Openfort.OpenfortSDK;
using Openfort.OpenfortSDK.Model;
 
public class OpenfortOAuthManager : MonoBehaviour 
{
    private OpenfortSDK openfort;
    
    private async void Start()
    {
        try
        {
            openfort = await OpenfortSDK.Init(
                "YOUR_OPENFORT_PUBLISHABLE_KEY",
                "YOUR_SHIELD_PUBLISHABLE_KEY" // Optional for OAuth only
            );
            Debug.Log("Openfort SDK initialized for OAuth authentication");
        }
        catch (Exception e)
        {
            Debug.LogError(quot;Failed to initialize Openfort: {e.Message}");
        }
    }
}

Authenticate with OAuth

To authenticate users with OAuth providers:

public class OpenfortOAuthManager : MonoBehaviour 
{
    // ... previous code ...
 
    public async UniTask<AuthPlayerResponse> AuthenticateWithOAuth(OAuthProvider provider)
    {
        try
        {
            // Create OAuth request with platform-specific settings
            var request = new OAuthInitRequest
            {
                Provider = provider,
#if UNITY_WEBGL || UNITY_STANDALONE_WIN
                // Use pooling for platforms that can't handle redirects
                UsePooling = true,
#else
                // Use redirect flow for mobile and other platforms
                UsePooling = false,
                Options = new OAuthInitRequestOptions
                {
                    RedirectTo = "mygame://callback" // Your custom URL scheme
                },
#endif
            };
            
            Debug.Log(quot;Starting OAuth authentication with {provider}...");
            
            // Start the OAuth flow
            bool authSuccess = await openfort.AuthenticateWithOAuth(request);
            
            if (!authSuccess)
            {
                throw new Exception("OAuth authentication was cancelled or failed");
            }
            
            // Get the authenticated user
            var userResponse = await openfort.GetUser();
            Debug.Log(quot;User logged in successfully with {provider}: {userResponse.Id}");
            
            // Log linked accounts
            foreach (var account in userResponse.LinkedAccounts)
            {
                Debug.Log(quot;Linked account: {account.Provider} - {account.Email}");
            }
            
            return userResponse;
        }
        catch (OpenfortException e)
        {
            Debug.LogError(quot;Openfort OAuth error: {e.Message}, Type: {e.ErrorType}");
            throw;
        }
        catch (Exception e)
        {
            Debug.LogError(quot;OAuth authentication failed: {e.Message}");
            throw;
        }
    }
    
    // Initialize OAuth with a specific provider
    public async UniTask<InitAuthResponse> InitOAuth(OAuthProvider provider)
    {
        try
        {
            var request = new OAuthInitRequest
            {
                Provider = provider,
                UsePooling = false
            };
            
            var response = await openfort.InitOAuth(request);
            Debug.Log(quot;OAuth initialization URL: {response.Url}");
            
            return response;
        }
        catch (Exception e)
        {
            Debug.LogError(quot;Failed to initialize OAuth: {e.Message}");
            throw;
        }
    }
}

Platform-specific configuration

The OAuth flow differs based on the platform:

  • WebGL & Standalone Windows: Uses pooling mode where the SDK handles the OAuth flow internally
  • Mobile & Other Platforms: Uses redirect mode with a custom URL scheme (e.g., mygame://callback)

Available providers

You can use any of the following OAuth providers:

// Available OAuth providers in the Openfort SDK
public enum OAuthProvider
{
    GOOGLE,
    DISCORD, 
    TWITTER,
    FACEBOOK,
    EPIC,
    OIDC,
    APPLE // Available on iOS
}
 
// Example usage:
// await authManager.AuthenticateWithOAuth(OAuthProvider.GOOGLE);

Authentication response

Upon successful authentication, you'll receive a response containing:

{
  "player": {
      "id": "pla_cc9ed2b7-c5f5-4c43-8dca-c4b104ba1762",
      "object": "player",
      "createdAt": 1710976453,
      "linkedAccounts": [
          {
              "provider": "google",
              "disabled": false,
              "verified": true,
              "email": "user@gmail.com"
          }
      ]
  },
  "token": "eyJhbGci...",
  "refreshToken": "eyJhbGci..."
}

Log out

To log out a user:

await openfort.Logout();

UI integration example

Here's a complete example of integrating OAuth authentication with Unity UI:

using UnityEngine.UI;
using TMPro;
using Cysharp.Threading.Tasks;
 
public class OAuthUIManager : MonoBehaviour
{
    [Header("UI References")]
    [SerializeField] private Button googleButton;
    [SerializeField] private Button discordButton;
    [SerializeField] private Button twitterButton;
    [SerializeField] private GameObject loadingIndicator;
    [SerializeField] private TextMeshProUGUI statusText;
    [SerializeField] private GameObject loginPanel;
    [SerializeField] private GameObject gamePanel;
    
    private OpenfortOAuthManager authManager;
 
    private void Start()
    {
        authManager = GetComponent<OpenfortOAuthManager>();
        SetupButtonListeners();
        
        // Hide game panel initially
        gamePanel?.SetActive(false);
    }
    
    private void SetupButtonListeners()
    {
        googleButton?.onClick.AddListener(() => HandleOAuthLogin(OAuthProvider.GOOGLE).Forget());
        discordButton?.onClick.AddListener(() => HandleOAuthLogin(OAuthProvider.DISCORD).Forget());
        twitterButton?.onClick.AddListener(() => HandleOAuthLogin(OAuthProvider.TWITTER).Forget());
    }
 
    private async UniTaskVoid HandleOAuthLogin(OAuthProvider provider)
    {
        UpdateUI(true, quot;Connecting with {provider}...");
        
        try
        {
            var userResponse = await authManager.AuthenticateWithOAuth(provider);
            
            // Success - show game UI
            UpdateUI(false, quot;Welcome, {GetUserDisplayName(userResponse)}!");
            ShowGamePanel();
        }
        catch (Exception e)
        {
            UpdateUI(false, quot;Login failed: {e.Message}");
            Debug.LogError(quot;OAuth login failed: {e.Message}");
        }
    }
    
    private void UpdateUI(bool isLoading, string message)
    {
        if (loadingIndicator != null)
            loadingIndicator.SetActive(isLoading);
            
        if (statusText != null)
            statusText.text = message;
            
        SetButtonsInteractable(!isLoading);
    }
 
    private void SetButtonsInteractable(bool interactable)
    {
        if (googleButton != null) googleButton.interactable = interactable;
        if (discordButton != null) discordButton.interactable = interactable;
        if (twitterButton != null) twitterButton.interactable = interactable;
    }
    
    private void ShowGamePanel()
    {
        loginPanel?.SetActive(false);
        gamePanel?.SetActive(true);
    }
    
    private string GetUserDisplayName(AuthPlayerResponse user)
    {
        // Try to get email from linked accounts
        foreach (var account in user.LinkedAccounts)
        {
            if (!string.IsNullOrEmpty(account.Email))
            {
                return account.Email.Split('@')[0]; // Use part before @
            }
        }
        
        return user.Id.Substring(0, 8); // Fallback to user ID prefix
    }
    
    // Optional: Handle logout
    public async UniTaskVoid HandleLogout()
    {
        try
        {
            await authManager.openfort.Logout();
            loginPanel?.SetActive(true);
            gamePanel?.SetActive(false);
            UpdateUI(false, "Logged out successfully");
        }
        catch (Exception e)
        {
            Debug.LogError(quot;Logout failed: {e.Message}");
        }
    }
}