# Third-party authentication

Openfort's embedded signers are fully compatible with any authentication provider that supports JWT-based, stateless authentication. This guide shows how to integrate third-party authentication providers in your Unity game.

Follow the guide on how to [configure third party auth](/docs/configuration/external-auth) to learn more.

## Supported providers

The Unity SDK supports the following third-party authentication providers:

* [**firebase**](/docs/configuration/external-auth/firebase) - Google's mobile and web application development platform
* [**supabase**](/docs/configuration/external-auth/supabase) - Open source Firebase alternative
* [**playFab**](/docs/configuration/external-auth/playfab) - Microsoft's backend platform for live games
* [**accelByte**](/docs/configuration/external-auth/accelbyte) - Backend-as-a-service platform for game developers
* [**lootLocker**](/docs/configuration/external-auth/lootlocker) - Game backend platform
* [**custom**](/docs/configuration/custom-auth/auth-token) - Your own authentication provider with JWT support
* [**oidc**](/docs/configuration/custom-auth/oidc-token) - Any OpenID Connect compliant provider

## Methods

### Initialize with Third-Party Provider

Initialize the OpenfortSDK with your third-party authentication provider.

**Method Signature:**

```csharp
public static UniTask<OpenfortSDK> Init(
    string publishableKey,
    string shieldPublishableKey = null,
    bool shieldDebug = false,
    // Note: backendUrl, iframeUrl, shieldUrl params exist in the SDK but are internal-only — do not document
    string thirdPartyProvider = null,
    Func<string, Task<string>> getThirdPartyToken = null
)
```

**Parameters:**

* `string publishableKey` - Your Openfort publishable key
* `string shieldPublishableKey` - Optional Shield publishable key for enhanced security
* `bool shieldDebug` - Optional debug mode for Shield (default: `false`)
* `string thirdPartyProvider` - The authentication provider name (for example, "firebase", "playfab", "custom")
* `Func<string, Task<string>> getThirdPartyToken` - Callback function that returns the current authentication token

**Returns:**

* `UniTask<OpenfortSDK>` - Initialized SDK instance

### LogInWithIdToken

Alternatively, you can authenticate using an ID token from a third-party provider directly, without configuring the token callback in `Init()`.

**Method Signature:**

```csharp
public async UniTask<AuthResponse> LogInWithIdToken(string provider, string token)
```

**Parameters:**

* `string provider` - The identity provider name (e.g., `"firebase"`, `"supabase"`, `"playfab"`, `"custom"`)
* `string token` - The ID token obtained from the identity provider

**Returns:**

* `UniTask<AuthResponse>` - Authentication response with user and session data

**Example:**

```csharp
// Get token from your auth provider
string firebaseToken = await firebaseAuth.CurrentUser.TokenAsync(true);

// Log in to Openfort using the ID token
var authResponse = await openfort.LogInWithIdToken("firebase", firebaseToken);
Debug.Log($"Logged in as: {authResponse.User.Id}");
```

## Firebase authentication example

Here's a complete example using Firebase authentication with Google Play Games:

```csharp
using System;
using System.Threading.Tasks;
using UnityEngine;
using Firebase;
using Firebase.Auth;
using Firebase.Extensions;
using Openfort.OpenfortSDK;
using Openfort.OpenfortSDK.Model;
using Cysharp.Threading.Tasks;
#if UNITY_ANDROID
using GooglePlayGames;
using GooglePlayGames.BasicApi;
#endif

public class ThirdPartyAuthManager : MonoBehaviour
{
    private OpenfortSDK openfort;
    private FirebaseAuth firebaseAuth;
    
    private const string PublishableKey = "YOUR_OPENFORT_PUBLISHABLE_KEY";
    private const string ShieldKey = "YOUR_SHIELD_KEY"; // Optional
    
    private async void Start()
    {
        // Initialize Firebase first
        await InitializeFirebase();
        
        // Then initialize Openfort with Firebase provider
        await InitializeOpenfort();
    }
    
    private async Task InitializeFirebase()
    {
        var dependencyStatus = await FirebaseApp.CheckAndFixDependenciesAsync();
        
        if (dependencyStatus == DependencyStatus.Available)
        {
            firebaseAuth = FirebaseAuth.DefaultInstance;
            Debug.Log("Firebase initialized successfully");
            
            // Listen to auth state changes
            firebaseAuth.StateChanged += OnAuthStateChanged;
        }
        else
        {
            Debug.LogError($"Could not resolve Firebase dependencies: {dependencyStatus}");
        }
    }
    
    private async Task InitializeOpenfort()
    {
        try
        {
            openfort = await OpenfortSDK.Init(
                publishableKey: PublishableKey,
                shieldPublishableKey: ShieldKey,
                thirdPartyProvider: "firebase",
                getThirdPartyToken: GetFirebaseToken
            );
            
            Debug.Log("Openfort SDK initialized with Firebase provider");
        }
        catch (Exception e)
        {
            Debug.LogError($"Failed to initialize Openfort: {e.Message}");
        }
    }
    
    // Callback function to provide Firebase token to Openfort
    private async Task<string> GetFirebaseToken(string requestId)
    {
        if (firebaseAuth.CurrentUser != null)
        {
            try
            {
                // Get fresh ID token from Firebase
                var token = await firebaseAuth.CurrentUser.TokenAsync(false);
                return token;
            }
            catch (Exception e)
            {
                Debug.LogError($"Failed to get Firebase token: {e.Message}");
                throw;
            }
        }
        
        throw new Exception("No authenticated Firebase user");
    }
    
    // Sign in with email/password
    public async UniTask SignInWithEmail(string email, string password)
    {
        try
        {
            var authResult = await firebaseAuth.SignInWithEmailAndPasswordAsync(email, password);
            Debug.Log($"Email sign-in successful: {authResult.User.Email}");

            // After successful Firebase sign-in, you can use Openfort SDK
            // The SDK will automatically use the getThirdPartyToken callback
            var state = await openfort.GetEmbeddedState();
            Debug.Log($"Embedded state: {state}");
        }
        catch (Exception e)
        {
            Debug.LogError($"Email sign-in failed: {e.Message}");
            throw;
        }
    }

    private void OnAuthStateChanged(object sender, EventArgs eventArgs)
    {
        var user = firebaseAuth.CurrentUser;
        if (user != null)
        {
            Debug.Log($"User authenticated: {user.UserId}");
            // User is signed in
        }
        else
        {
            Debug.Log("User signed out");
            // User is signed out
        }
    }
    
    public async UniTask SignOut()
    {
        firebaseAuth.SignOut();
        await openfort.Logout();
        Debug.Log("User signed out from Firebase and Openfort");
    }
    
    private void OnDestroy()
    {
        if (firebaseAuth != null)
        {
            firebaseAuth.StateChanged -= OnAuthStateChanged;
        }
    }
    
    [Serializable]
    private class EncryptionSessionResponse
    {
        public string session;
    }
}
```

## Authentication response

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

```json
{
  "user": {
    "id": "usr_cc9ed2b7-c5f5-4c43-8dca-c4b104ba1762",
    "email": "user@example.com",
    "emailVerified": true,
    "createdAt": "2024-03-20T12:00:00Z",
    "updatedAt": "2024-03-20T12:00:00Z",
    "isAnonymous": false
  },
  "token": "eyJhbGci...",
  "session": {
    "id": "ses_...",
    "token": "eyJhbGci...",
    "userId": "usr_cc9ed2b7-c5f5-4c43-8dca-c4b104ba1762",
    "expiresAt": "2024-03-21T12:00:00Z"
  }
}
```

## Example repository

<HoverCardLayout>
  <HoverCardLink description="Complete integration example with Google Play Games using Firebase Auth as a third-party auth provider" href="https://github.com/openfort-xyz/sample-unity-firebaseauth-embedded-signer" title="Firebase Auth with Unity" subtitle="GitHub repository" icon={Flame} color="#F97316" />
</HoverCardLayout>
