【问题标题】:gmail API deleting eMails using service accountgmail API使用服务帐户删除电子邮件
【发布时间】:2021-09-29 14:10:38
【问题描述】:

我正在尝试阅读和删除我的邮件以进行一些自动化测试,我的问题是我不能使用 oauth,因为它需要用户输入。所以我试图使用服务帐户

但是当我运行我的代码时,我得到了一个错误

现在我想知道我的代码或我在 Google 控制台中的权限是否有问题

错误:

'发生一个或多个错误。 (错误:“unauthorized_client”,描述:“客户端未授权使用此方法检索访问令牌,或客户端未授权任何请求的范围。”,Uri:“”)'

出现在这里:credential.RequestAccessTokenAsync(CancellationToken.None).Result

代码

        private ServiceAccountCredential credential;
        private GmailService Service { get; set; }

        // If modifying these scopes, delete your previously saved credentials
        private static string[] Scopes = { GmailService.Scope.MailGoogleCom };
        private static string applicationName = "EmailReader";
        private static string credentialsFile = "emailreader-289206-c91027110691.p12";
        private static string keyPassword = "notasecret";
        private static string serviceAccountEmail = "auristesterdienstkonto@emailreader-289206.iam.gserviceaccount.com";
        private static string userEmail = "auristester1@gmail.com";

        private Func<Message, bool> lastFilter;

        public GmailLibary() //my constructor
        {
            var certificate = new X509Certificate2(
                credentialsFile,
                keyPassword,
                X509KeyStorageFlags.Exportable);

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

            if (credential.RequestAccessTokenAsync(CancellationToken.None).Result)
            {
                Service = new GmailService(
                    new BaseClientService.Initializer()
                    {
                        ApplicationName = applicationName,
                        HttpClientInitializer = credential
                    }
                );
            }
        }

权限

【问题讨论】:

    标签: c# google-oauth gmail-api google-workspace service-accounts


    【解决方案1】:

    “客户端未授权使用此方法检索访问令牌,或客户端未授权任何请求的范围。”

    通常意味着您正在使用服务帐户的代码,但您尚未在 Google 云控制台上创建服务帐户凭据。确保您设置的服务帐户也出现在google cloud console 我不确定在谷歌云平台上创建的服务帐户是否相同。 (不是我测试过。)

    对于 Gmail API,这也是您没有在您的 google 工作区帐户中正确设置 domain wide delegation 的结果。请记住,服务帐户仅适用于带有您的域电子邮件之一的 gmail api,而您不能将其与标准 gmail 电子邮件一起使用。

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 2020-11-01
      • 2016-01-18
      • 2016-04-20
      • 2020-04-05
      • 2017-05-31
      • 2012-03-30
      • 2021-12-16
      • 2017-05-14
      相关资源
      最近更新 更多