【发布时间】:2018-06-18 19:05:58
【问题描述】:
当我使用Google.Apis.Auth.OAuth2.UserCredential 进行授权时,我的代码运行良好。当我切换到Google.Apis.Auth.OAuth2.ServiceAccountCredential 时,相同的代码不起作用。
问题可能出在以下三个地方之一:
-
1)。我是否正确构建了
ServiceAccountCredential?2)。我是否正确使用
ServiceAccountCredential来访问 用户帐户?3)。 GA 管理员是否为服务帐户提供了适当的读取权限 用户的邮件?
这是不工作的代码:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Services;
using Google.Apis.Discovery.v1;
using Google.Apis.Discovery.v1.Data;
using Google.Apis.Util.Store;
string[] asScopes = { GmailService.Scope.GmailModify };
string msApplicationName = "Gmail API .NET Quickstart";
string sClientEmail = "blah@blah.gserviceaccount.com" //service account;
string sUser = "cfo@mydomain.com" //email of the user that I want to read;
string sPrivateKey = "-----BEGIN PRIVATE KEY----- blah"//service account private key;
string[] asScopes = {"https://mail.google.com/"};
//get credential
ServiceAccountCredential oCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(sClientEmail)
{
Scopes = asScopes,
User = sUser //the user to be impersonated
}.FromPrivateKey(sPrivateKey));
// Create Gmail API service.
GmailService oSVC = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = oCred,
ApplicationName = msApplicationName,
});
// List labels.
UsersResource.LabelsResource.ListRequest request = oSVC.Users.Labels.List("me");
IList<Google.Apis.Gmail.v1.Data.Label> labels = request.Execute().Labels; //<--error here.
/* --- fails with:
Google.Apis.Auth.OAuth2.Responses.TokenResponseException was unhandled HResult=-2146233088 Message=Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method.", Uri:"" Source=Google.Apis.Auth
*/
如果有人可以提供有关如何测试ServiceAccountCredential 以查看其构造是否正确的示例以及它已获得授权的示例,我将不胜感激。
所有这一切中一个令人烦恼的问题是,我是否可以从 PrivateKey 创建一个ServiceAccountCredential,因为我看到的所有示例都使用证书,例如:
var certificate = new X509Certificate2("key2.p12", "notasecret",
X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
string userEmail = "abc@gmail.com";
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new string[] { Gmail.v1.GmailService.Scope.GmailReadonly }
}.FromCertificate(certificate)
);
【问题讨论】:
-
首先,您是否查看了关于服务帐户的实施Server-Side Authorization 指南?
-
@nogui - 您的链接指向 UserAuth,而不是 SerbiceAuth,您的链接与我的工作无关。如果您问我是否阅读了文档:是的,我阅读了所有谷歌文档,并且确实花了很长时间查看托管 .net 代码的 github cmets,然后在 SO 上发布。
标签: c# .net gmail-api google-api-dotnet-client