刚刚开始使用 Google API。
在我的 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] /cdn-cgi/l/email-protection") //service Account id
{
Scopes = Scopes,
User = "[email protected] /cdn-cgi/l/email-protection" //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 https://stackoverflow.com/users/1975000/peleyal)有更好的想法直接通过 GoogleCredential 来完成,请随时给我提示;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)