无法从Google获得服务帐户的访问令牌

时间:2020-03-25 14:00:06

标签: c# gmail-api google-workspace

我正在尝试配置能够与Gmail API一起使用的应用程序。如您所知,必须使用访问令牌。请求令牌的方法有多种,但是对我来说,应该是一个服务帐户,因为将来该程序代码将在Windows Service中...(因此,没有机会通过从Windows重定向手动接收令牌)。 Google URL,只有网络请求和响应才是出路)

所以,我已经做了:

  1. 在Google Cloud Platform中创建了新项目;
  2. 在此项目中创建了新的服务帐户(根据此处提到的步骤:https://developers.google.com/identity/protocols/oauth2/service-account#creatinganaccount);
  3. 生成并下载* .P12密钥;
  4. 启用了域范围的委派(在许多类似问题中建议的步骤4之前);
  5. 授权G Suite管理员帐户中的范围“ https://mail.google.com/”获得正确的客户ID(根据此处提到的步骤:https://developers.google.com/identity/protocols/oauth2/service-account#delegatingauthority);
  6. 使用以下简单代码进行授权和请求令牌:
            const string serviceAccountEmail = "***test@oauthtester-271011.iam.gserviceaccount.com";
            const string serviceAccountCertPath = @"C:\Users\user\Documents\Visual Studio 2017\Projects\OAuthTester\OAuthTester\bin\Debug\oauthtester-271011-bd2cced31ea5.p12";
            const string serviceAccountCertPassword = "notasecret";
            const string userEmail = "***oauthtest@***.com";

            X509Certificate2 certificate = new X509Certificate2(
                serviceAccountCertPath,
                serviceAccountCertPassword,
                X509KeyStorageFlags.Exportable);

            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                    Scopes = new[] { GoogleScope.ImapAndSmtp.Name }, //"https://mail.google.com/"
                    User = userEmail
                }.FromCertificate(certificate));


            credential.RequestAccessTokenAsync(CancellationToken.None).Wait();

不幸的是,我遇到了一个错误:

Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.

我也尝试过:

  1. 要将serviceAccountEmail更改为ClientId;
  2. 要创建,删除并再次在G Suite中添加同一客户ID的授权访问权限;
  3. 要删除并创建另一个服务帐户,然后在G Suite中授权新的客户ID。

不幸的是,每次我遇到相同的错误。也许有人猜到我做错了什么?

0 个答案:

没有答案
相关问题