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

时间:2015-08-05 14:49:30

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

我正在构建一个需要阅读普通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:""

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

感谢任何帮助!

更新

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

1 个答案:

答案 0 :(得分:0)

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

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

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

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