Ash
Ash

Reputation: 93

Firebase IDToken to Google OAuth2 access token in Unity

We use Firebase Auth in our Unity game and Google SignIn and need to access Google services like Google Classroom.

Firebase Auth gives us a JWT IdToken after signing in using this code https://firebase.google.com/docs/auth/admin/verify-id-tokens#unity

Firebase.Auth.FirebaseUser newUser = task2.Result;
var token = await newUser.TokenAsync(false); 

I tried passing this token to Google Classroom service but it requires an OAuth2 AccessToken.

How I convert this JWT Firebase IdToken to an AccessToken that can be used by the GoogleClassroom API?

I am looking for the AccessToken to pass to the Google Classroom APIs

var credential = GoogleCredential.FromAccessToken(AccessToken);
var service = new ClassroomService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });

I have tried the answer to this question but the service is returning 404.

Upvotes: 5

Views: 2143

Answers (1)

Vikas Patel
Vikas Patel

Reputation: 51

You are trying to get google access token..! You can simply get it by a simple API call.

IEnumerator GetAccessToken()
        {
            WWWForm form = new WWWForm();
            form.AddField("client_id", "your_webClientId");
            form.AddField("client_secret", "your_clientsecret");
            form.AddField("grant_type", "authorization_code");
            form.AddField("code", "your_authcode);
            UnityWebRequest www = UnityWebRequest.Post("https://www.googleapis.com/oauth2/v4/token", form);
            yield return www.SendWebRequest();

            if (www.isNetworkError || www.isHttpError)
            {
            }
            else
            {

                //Access token response
                GoogleData googleData =JsonUtility.FromJson<GoogleData>(www.downloadHandler.text); 
                Debug.LogError(googleData.access_token);
                
            }
        }

In the API success you can parse the response in to data model class. NOTE:Do not chane "grant_type" field value.

[System.Serializable]
    public class GoogleData
    {
        public string access_token;
        public string token_type;
        public int expires_in;
        public string refresh_token;
    }

Upvotes: 5

Related Questions