【问题标题】:Gmail API service accountGmail API 服务帐号
【发布时间】:2017-01-23 10:40:29
【问题描述】:

我想使用 Gmail API 阅读我的 Gmail 收件箱。由于我的应用程序没有用户交互,我需要使用服务帐户。 根据要求,我收到以下错误:

"InnerException = {"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\""} "

这是我的代码:

        string applicationName = "Gmail API .NET";
        string[] scopes = { GmailService.Scope.GmailReadonly };

        string certPath = "./XXXXXXXXXX.p12";
        string userEmail = "MYEMAIL@gmail.com";
        string serviceAccountEmail = "MYSERVICEACCOUNT...am.gserviceaccount.com";

        //Carga el certificado obtenido de 
        var certificate = new X509Certificate2(certPath, "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                User = userEmail,
                Scopes = scopes
            }.FromCertificate(certificate)
        );

        if (credential.RequestAccessTokenAsync(CancellationToken.None).Result) <--- Here I get the error
        {
            GmailService gs = new GmailService(
                new BaseClientService.Initializer()
                {
                    ApplicationName = applicationName,
                    HttpClientInitializer = credential
                }
            );
        }

我做错了什么?有人可以帮帮我吗?

问候

【问题讨论】:

  • 您需要配置您的 Gmail 帐户以允许 POP3/SMTP 访问。您可以在您的 Gmail 在线设置中执行此操作。
  • 谢谢。我做到了,但我得到了相同的结果:(
  • 试试这个。 ebstalimited.zendesk.com/hc/en-us/articles/…您还需要 G Suite 才能使用服务帐号。

标签: c# oauth-2.0 gmail-api service-accounts


【解决方案1】:

尝试检查documentation 关于 .NET 库中的服务帐户。本文档还为您提供了一个示例代码,您可以按照它来了解如何设置服务帐户。这个link 还可以让您了解如何使用服务帐户访问 GMAIL API。

现在,对于您收到的错误,请检查此链接是否可以帮助您。

【讨论】:

    【解决方案2】:

    您只能使用服务帐号为 GSuite 帐号而非 gmail 帐号发送电子邮件。

    如果您有 gmail 帐户,则可以使用 3-legged OAuth2 authentication 或者打开 2FA,生成 App Password 并使用 here

    如果您使用的是 GSuite 帐户,则可以使用 ServiceAccount,但您必须确保它具有 G Suite 域范围委派,如 here 所述,然后您需要授予访问权限描述的 G Suite 域here

    【讨论】:

      【解决方案3】:

      您是否尝试过 Google 提供的用于此功能的示例代码?

        using Google.Apis.Gmail.v1;
       using Google.Apis.Gmail.v1.Data;
      
       // ...
      
       public class MyClass {
      
         // ...
      
       /// <summary>
       /// Retrieve a Message by ID.
       /// </summary>
       /// <param name="service">Gmail API service instance.</param>
       /// <param name="userId">User's email address. The special value "me"
       /// can be used to indicate the authenticated user.</param>
       /// <param name="messageId">ID of Message to retrieve.</param>
       public static Message GetMessage(GmailService service, String userId, String messageId)
       {
           try
           {
               return service.Users.Messages.Get(userId, messageId).Execute();
           }
           catch (Exception e)
           {
               Console.WriteLine("An error occurred: " + e.Message);
           }
      
           return null;
       }
      
       // ...
      
      }
      

      您是否尝试过这里的 API 浏览器:https://developers.google.com/gmail/api/v1/reference/users/messages/get#net 并输入您的请求信息?它在 API 页面上有效吗?

      【讨论】:

      • 来自谷歌的测试工作正常。我认为问题在于身份验证。当我调用此方法 credential.RequestAccessTokenAsync(CancellationToken.None) 时,我收到此错误 {"Error:\"unauthorized_client\", Description:\"Unauthorized client or scope in request.\", Uri:\"\""}。结果
      【解决方案4】:

      服务帐号无法访问@gmail.com 邮箱。您必须使用https://developers.google.com/identity/protocols/OAuth2 中描述的其他受支持的 OAuth 2.0 授权方案之一。

      https://stackoverflow.com/a/39534420/3377170了解更多详情。

      【讨论】:

      • 我设法使用了一个旧的 Gmail 帐户。测试是使用新帐户完成的。如果旧帐户允许您使用服务帐户,是否有可能?
      • 过去存在允许服务帐户访问@gmail.com 帐户的漏洞,但现已关闭。见stackoverflow.com/a/39534420/3377170
      猜你喜欢
      • 2014-09-13
      • 2020-09-23
      • 2016-12-19
      • 1970-01-01
      • 2020-12-20
      • 2022-01-15
      • 2015-06-28
      • 2021-06-22
      • 2015-01-18
      相关资源
      最近更新 更多