Search code examples
unity-game-enginefirebase-realtime-databasefirebase-authenticationfirebase-cloud-messagingunity-editor

Firebase Bearer Token


I'm now working on RestAPI calls from Unity Editor to Firebase Cloud Messaging and Firebase Realtime Database. Here the code what I'm using to create a token with multiply scores.

private static readonly string[] _scores = new[]
        {
            "https://www.googleapis.com/auth/userinfo.email",
            "https://www.googleapis.com/auth/firebase.database",
            "https://www.googleapis.com/auth/firebase.messaging"
        };

public string CreateToken(DateTimeOffset now, string[] scores)
        {
            var nowSeconds = now.ToUnixTimeSeconds();
            var inOneHour = GetExpirationTime(now);

            var scope = string.Join(",", scores);

            var payload = new Dictionary<string, object>
            {
                { "iss", _serviceAccountData.ClientEmail },
                { "scope", scope },
                { "aud", _serviceAccountData.TokenUri },
                { "iat", nowSeconds },
                { "exp", inOneHour }
            };

            return SignToken(payload);
        }

But this not working, calls to https://fcm.googleapis.com/v1/projects/{0}/messages:send returns 401 Unauthorized. If I'm passing only https://www.googleapis.com/auth/firebase.messaging as scope everything working. But I still need to call firebase realtime database. Is that possible to use same Bearer Token to call both APIs or I need to have 2 different tokens for such a behavior?

I have "firebase_admin_sdk.json" in project and Jose.JWT to sign request.


Solution

  • Fixed with removing comma from scopes and splitting tokens for messaging and realtime database.