ReneDev
ReneDev

Reputation: 171

GoogleCredential created by json private key file (ServiceAccount) - how to set the User to impersonate?

just starting with Google Apis. In my Google Cloud Platform account i created a Service Account for domain wide delegation. I saved a private key file in json format for this service account.

In my test application i am creating a GoogleCredential instance:

var credential = 
            GoogleCredential.FromStream(new FileStream("privatekey.json", FileMode.Open, FileAccess.Read))
            .CreateScoped(Scopes);

How can i set the user i want to impersonate? When using a p12 private key i could do the following:

var credential = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer("[email protected]") //service Account id
    {
       Scopes = Scopes,
       User = "[email protected]" //the user to be impersonated                    
    }.FromCertificate(new X509Certificate2(@"xxx.p12", "notasecret", X509KeyStorageFlags.Exportable)));

But how can i do this "the easy way" with GoogleCredential and a json privatkey file?

Kind regards

Upvotes: 7

Views: 11904

Answers (3)

Vasioky
Vasioky

Reputation: 121

A easier way is this

var sac = ServiceAccountCredential.FromServiceAccountData(new FileStream("key.json", FileMode.Open));

Upvotes: 1

ReneDev
ReneDev

Reputation: 171

Ok i solved it now by copying code from the insides of GoogleCredential and the internal class DefaultCredentialProvider

using (var fs = new FileStream("key.json", FileMode.Open, FileAccess.Read))
{
    var credentialParameters =
        NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(fs);
    if (credentialParameters.Type != "service_account" 
        || string.IsNullOrEmpty(credentialParameters.ClientEmail) 
        || string.IsNullOrEmpty(credentialParameters.PrivateKey))
            throw new InvalidOperationException("JSON data does not represent a valid service account credential.");
    return new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
        {
            Scopes = Scopes,
            User = _adminUser //the user to be impersonated
        }.FromPrivateKey(credentialParameters.PrivateKey));
}

If someone (maybe peleyal) has a better idea to do it directly via GoogleCredential feel free to give me a hint ;)

Upvotes: 8

turtlepower
turtlepower

Reputation: 758

Javascript below but you can do similar in #C I'm sure.

I use the client_id and client_secret approach

function tokenRefresh(){

  var uri = "https://accounts.google.com/o/oauth2/token";

  var payload =
      {
        'client_id' : 'XXXXXXXX.apps.googleusercontent.com',
        'client_secret' : 'XXXXXXXX',
        'grant_type' : 'refresh_token',
        'content_type' : 'application/x-www-form-urlencoded',
        'refresh_token' : 'XXXXXXXX'
      };

  var options = 
      { "method" : "POST",
       "muteHttpExceptions" : false,
       "payload" : payload
      };

  var response = UrlFetchApp.fetch(uri, options),
      response_json = JSON.parse(response.getContentText()),
      token = response_json.access_token;
  return(token);
}

This will give you a new token every time, assuming you have the correct scope permissions.

You will need to append access_key everytime you want to access the API (rather than the 'key=' indicated by some of Google's docs)

For more information on how to get scope feel free to check out what I wrote: http://thisistony.com/blog/googleanalytics/google-analytics-api-oauth-ever-wondered-how-to-get-the-access_token/

Upvotes: 0

Related Questions