Hi, I’m trying to create a virtual friend in Unity for iOS, where I use the Vertex AI model Gemini Flash for communication, but I can’t just use an API key for that communication; Vertex AI need OAuth 2.0 authentication. I tried code using the Google.Apis.Auth.OAuth2 library, but it seems to not work when building for iOS. Is there an alternative option?
using System;
using System.IO;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using UnityEngine;
public class GoogleCloudAuthHelper : MonoBehaviour
{
public string apiKeyPath = "service-account";
private GoogleCredential _credential;
private string _accessToken;
private async void Awake()
{
await InitializeCredential();
}
private async Task InitializeCredential()
{
try
{
Debug.Log($"Attempting to load service account JSON file from path: {apiKeyPath}");
// Load the service-account.json file as a TextAsset from Resources
string resourcePath = Path.GetFileNameWithoutExtension(apiKeyPath);
TextAsset jsonKeyAsset = Resources.Load<TextAsset>(resourcePath);
if (jsonKeyAsset == null)
{
throw new FileNotFoundException($"Service account JSON file not found at path: {resourcePath}");
}
Debug.Log("Service account JSON file loaded successfully.");
// Create a memory stream from the TextAsset content
using (var jsonKeyStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(jsonKeyAsset.text)))
{
// Create Google Credential from the loaded JSON key
_credential = GoogleCredential.FromStream(jsonKeyStream)
.CreateScoped(new[] { "https://www.googleapis.com/auth/cloud-platform" });
}
Debug.Log("Google Credential initialized successfully.");
// Obtain the access token
_accessToken = await GetAccessTokenAsync();
}
catch (Exception ex)
{
Debug.LogError($"Failed to initialize Google credentials: {ex.Message}");
}
}
public async Task<string> GetAccessTokenAsync()
{
if (_credential == null)
{
Debug.LogError("Google Credential is not initialized.");
return null;
}
if (_credential.UnderlyingCredential == null)
{
Debug.LogError("Underlying Credential is null.");
return null;
}
try
{
// Get the access token from the underlying credential
var tokenResponse = await _credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
Debug.Log("Access token obtained successfully.");
return tokenResponse;
}
catch (Exception ex)
{
Debug.LogError($"Failed to obtain access token: {ex.Message}");
throw;
}
}
public GoogleCredential GetCredential()
{
if (_credential == null)
{
Debug.LogError("Google Credential is not initialized.");
}
return _credential;
}
public string GetStoredAccessToken()
{
return _accessToken;
}
}