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

别等时光非礼了梦想. 提交于 2019-12-07 01:45:01

问题


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("xxx@developer.gserviceaccount.com") //service Account id
    {
       Scopes = Scopes,
       User = "admin@xxx.com" //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


回答1:


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 ;)




回答2:


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/




回答3:


A easier way is this

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



来源:https://stackoverflow.com/questions/38496919/googlecredential-created-by-json-private-key-file-serviceaccount-how-to-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!