【问题标题】:Using Google API With Service Account Credentials on a non-domain account在非域帐户上使用具有服务帐户凭据的 Google API
【发布时间】:2015-10-28 10:16:05
【问题描述】:

我正在构建一个需要读取普通 Gmail 收件箱(不是域的一部分)的网络服务。

代码:

String serviceAccountEmail = "1234567890@developer.gserviceaccount.com";

var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable);

ServiceAccountCredential credentials = new ServiceAccountCredential(
    new ServiceAccountCredential.Initializer(serviceAccountEmail)
    {
        Scopes = new string[] { GmailService.Scope.GmailModify },
        User = "user@gmail.com"
    }.FromCertificate(certificate));

var service = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credentials,
    ApplicationName = ApplicationName,
});

UsersResource.MessagesResource.ListRequest allMessages = service.Users.Messages.List("me");

IList<Message> messages = allMessages.Execute().Messages;

错误:

An unhandled exception of type 'Google.Apis.Auth.OAuth2.Responses.TokenResponseException' occurred in Google.Apis.dll

Additional information: Error:"unauthorized_client", Description:"Unauthorized client or scope in request.", Uri:""

我看不出这不起作用的任何原因,但在阅读this 之后,您似乎无法在个人@gmail 帐户上使用服务帐户凭据。有谁知道这是真的还是我做错了什么?

感谢任何帮助!

更新

如果我将Scope 更改为GmailService.Scope.GmailReadonly,我可以查看邮件但无法修改标签,这是我的要求。

【问题讨论】:

  • 你可以试试大范围的Scopes = new[] { "https://mail.google.com/" }
  • 不幸的是,https://www.googleapis.com/auth/gmail.readonly 有效,但 https://mail.google.com/ 无效
  • 如果你想使用你的个人账户作为服务账户,那么更好的方法是使用 3-legged oauth 离线访问,因为服务账户不能自己行动,而模拟个人账户时,它会给出错误,因为只有域管理员可以这样做。
  • 感谢@SGC,是否有任何文档支持或解释为什么会这样?我想我会采取不同的方法,例如Imapx。看起来简单明了,不那么麻烦。
  • @Tom。抱歉,我找不到任何文档。

标签: c# google-api google-oauth gmail-api google-api-dotnet-client


【解决方案1】:

服务帐户是一个虚拟用户,可能在 gmail 帐户上拥有它,但我对此表示怀疑(我也从未测试过它)要让服务帐户能够访问您的数据,它必须获得访问权限。

就像任何其他用户一样,服务帐户将无法访问您的电子邮件,因为据我所知,无法授予其他人或服务帐户访问用户电子邮件的权限。

让我们以谷歌日历为例。如果我授予服务帐户电子邮件地址访问我帐户上的日历,它将能够从中读取。如果我授予它访问我的谷歌驱动器上的文件夹的权限,它也可以从中读取。基本上,您可以像添加任何其他用户一样将服务帐户电子邮件添加为用户,如果您可以这样做,那么服务帐户可以访问数据。

这在 Blogger 和 YouTube 上也不起作用,因为您不能添加电子邮件地址来让其他用户访问您的帐户。据我所知,没有办法授予其他人或电子邮件访问权限以阅读您的 gmail。您将需要使用 OAUTH2 并对用户进行身份验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-31
    • 1970-01-01
    相关资源
    最近更新 更多