【问题标题】:Gmail API stopped working suddenly. Error message says unauthorized_clientGmail API 突然停止工作。错误消息说 unauthorized_client
【发布时间】:2023-02-24 06:59:37
【问题描述】:

自过去 4 年以来,我们一直在使用 Gmail API 来阅读电子邮件,但它突然停止工作并抛出异常:Error: "unauthorized_client", Description: "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.", Uri:"

检查了服务帐户并且它是活动的,所以那里也没有问题。

提前致谢。

【问题讨论】:

  • 请编辑您的问题并包含您的代码。

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


【解决方案1】:

错误:“unauthorized_client”,说明:“客户端未授权使用此方法检索访问令牌,或者客户端未授权请求的任何范围。”,Uri:

这是一个相当常见的错误,我不确定为什么你现在首先得到它。

可与 .net 一起使用的 google Oauth 凭证有三种不同类型。桌面应用程序、安装的应用程序和服务帐户。

每个凭证都不同。使用它们的代码也不同。

您收到的错误消息表明您正在使用凭据及其非设计代码。

因此,如果您使用的是服务帐户,请确保

  1. 您使用的代码用于服务帐户。
  2. 您已使用您的 google workspace 帐户配置了域范围的委派。
  3. 确保工作区配置中没有任何更改。

    服务帐号

    您的代码应如下所示。

            string ApplicationName = "Gmail API .NET Quickstart";
            const string serviceAccount = "xxxx@xxxx.iam.gserviceaccount.com";
    
            var certificate = new X509Certificate2(@"D:xxxxx.p12", "notasecret", X509KeyStorageFlags.Exportable);
    
            var gsuiteUser = "User@YourDomain.com";
    
            var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(serviceAccount)
            {
                User = gsuiteUser,
                Scopes = new[] { GmailService.Scope.GmailSend, GmailService.Scope.GmailLabels }
    
            }.FromCertificate(certificate);
    
            var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
            if (!credential.RequestAccessTokenAsync(CancellationToken.None).Result)
                throw new InvalidOperationException("Access token failed.");
    
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = ApplicationName,
            });
    

    Gmail api with google workspace and .net

【讨论】:

    猜你喜欢
    • 2011-11-10
    • 2020-12-21
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-26
    • 2013-02-23
    相关资源
    最近更新 更多