Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 201
ReneDev Avatar asked Jul 21 '16 06:07

ReneDev


People also ask

How do I get a private key for Google Drive?

Keep the service account ID later for Google drive authentication during installation. Click Continue when prompted for entering service account permissions. Click on +Create Key and select P12 to create a private key. The P12 private key will be downloaded automatically, then click Done.


1 Answers

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

like image 160
ReneDev Avatar answered Oct 01 '22 06:10

ReneDev