在非域帐户上使用带有服务帐户凭证的Google API

本文关键字:凭证 服务 API Google | 更新日期: 2023-09-27 18:06:34

我正在构建一个需要读取正常Gmail收件箱(不是域名的一部分)的web服务。

代码:

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:""

我看不出这不起作用的任何原因,但读完这篇文章后,似乎你不能在个人gmail帐户上使用服务帐户凭据。有人知道这是真的吗,还是我做错了什么?

任何帮助都是感激的!

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

在非域帐户上使用带有服务帐户凭证的Google API

一个服务帐户是一个虚拟用户,可能有它的gmail帐户,但我怀疑它(我也从来没有测试过它)对于一个服务帐户能够访问你的数据,它必须被授予访问权限。

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

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

这也不能在Blogger和YouTube上工作,因为你不能添加一个电子邮件地址给另一个用户访问你的帐户。据我所知,没有办法允许其他人或电子邮件访问你的gmail。您需要使用OAUTH2并对用户进行身份验证。