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
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.
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 ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With