1
votes

I'm trying to get access token to Authenticate Google Service Account using below code. This code is returning a token. I tried to access the APIs from Postman with the token I received, however getting error as "Invalid IAP credentials: Base64 decode failed on token:". Just FYI, I'm using Google's OAuth library for .NET.

This is the token I received

ya29.c.Ko4B4Act579buZYyeoPgvOwuKREoi981lSLUQxA03SzAPGQuPY9Z3CXSnkouFdO4wj1lRwhGJxCLlnLlVsmLBySYf1VWQIbtSf8wMbIzW5b7n6mXeQgb-xk8SXwNZsLqxHprGlj-Zr35YrvoBzQPE6_OEQSD7g90g3Y-3DDnkCqs1m_K-udBVIVVYJ3lDQ

Code

class Program
{
    public const string SCOPE_READONLY = "https://www.googleapis.com/auth/userinfo.profile";
    public const string KEYFILE_PATH_READONLY = @"../../keys/XXXjson";
    public const string CLIENT_EMAIL_READONLY = "[email protected]";
    static void Main(string[] args)
    {
        var token = GoogleServiceAccount.GetAccessTokenFromJSONKey(
        KEYFILE_PATH_READONLY,
        SCOPE_READONLY);

        Console.WriteLine(token);
    }  
}

.

public class GoogleServiceAccount
    {
        /// <summary>
        /// Get Access Token From JSON Key Async
        /// </summary>
        /// <param name="jsonKeyFilePath">Path to your JSON Key file</param>
        /// <param name="scopes">Scopes required in access token</param>
        /// <returns>Access token as string Task</returns>
        public static async Task<string> GetAccessTokenFromJSONKeyAsync(string jsonKeyFilePath, params string[] scopes)
        {
            using (var stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read))
            {
                return await GoogleCredential
                    .FromStream(stream) // Loads key file
                    .CreateScoped(scopes) // Gathers scopes requested
                    .UnderlyingCredential // Gets the credentials
                    .GetAccessTokenForRequestAsync("https://accounts.google.com/o/oauth2/auth"); // Gets the Access Token
            }
        }

        /// <summary>
        /// Get Access Token From JSON Key
        /// </summary>
        /// <param name="jsonKeyFilePath">Path to your JSON Key file</param>
        /// <param name="scopes">Scopes required in access token</param>
        /// <returns>Access token as string</returns>
        public static string GetAccessTokenFromJSONKey(string jsonKeyFilePath, params string[] scopes)
        {
            return GetAccessTokenFromJSONKeyAsync(jsonKeyFilePath, scopes).Result;
        }

    }
1
IAP requires you to authenticate using an ID Token (which is a JWT), not with an access token. - Johannes Passing
Exactly. I just did it some hours back and found it working. Thanks for the update. - Shubham Sharma

1 Answers

1
votes

I was using incorrect way to get the token. The exact way via IAP is described here.