只是从Google Apis开始。
在我的Google Cloud Platform帐户中,我创建了一个用于域范围委派的服务帐户。我为此服务帐户以json格式保存了私钥文件。

在我的测试应用程序中,我正在创建一个GoogleCredential实例:

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

如何设置我要模拟的用户?
使用p12私钥时,我可以执行以下操作:
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)));

但是,我该如何使用GoogleCredential和json privatkey文件来“简便”呢?

亲切的问候

最佳答案

好的,我现在通过复制GoogleCredential和内部类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));
}

如果有人(也许peleyal)有更好的主意直接通过GoogleCredential进行操作,请给我一个提示;)

10-08 12:43