【问题标题】:Client is unauthorized to retrieve access tokens using this method or client not authorized for any scope requested API Directory C#客户端未经授权使用此方法检索访问令牌或客户端未授权任何范围请求的 API 目录 C#
【发布时间】:2022-09-19 16:43:01
【问题描述】:

尝试通过获取用户列表来访问目录 api 时出现以下错误

Google.Apis.Auth.OAuth2.Responses.TokenResponseException:错误:“unauthorized_client”,描述:“客户端未经授权无法使用此方法检索访问令牌,或者客户端未获得任何请求范围的授权。”,Uri:“”

根据我之前的谷歌搜索和阅读堆栈溢出,我不确定是什么原因造成的。据我所知,我已经正确设置了一切。我将其设置为以非常相似的方式使用驱动器 api,并且效果很好。

我的服务帐户确实具有域范围的委派,这就是为什么我认为它可能与错误的第二部分有关。有什么想法可能导致这种情况吗?

        protected async virtual Task<DirectoryService?> GetDirectoryService()
        {
            if (currentDirectory == null)
            {
                string[] scopes = new string[] { DirectoryService.Scope.AdminDirectoryUser };

                var initializer = new ServiceAccountCredential.Initializer(configuration["GoogleServiceAccount:AccountEmail"]){Scopes = scopes, User = configuration["GoogleServiceAccount:UserEmail"] };
                var cred = new ServiceAccountCredential(initializer.FromPrivateKey(configuration["GoogleServiceAccount:SecretKey"]));

                currentDirectory = new DirectoryService(new BaseClientService.Initializer { HttpClientInitializer = cred, ApplicationName = "DriveAPI" });
            }
            return currentDirectory;

【问题讨论】:

    标签: c# google-admin-sdk google-workspace service-accounts google-api-dotnet-client


    【解决方案1】:
    User = configuration["GoogleServiceAccount:UserEmail"]
    

    用户是您要委派的域中的用户,而不是服务帐户电子邮件地址。

    更新

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

    根据我的经验,此错误消息通常意味着您使用的代码与您使用的凭据类型不匹配。

    有几种类型的授权、服务帐户、安装的 Oauth 和 oauth web(现在让我们忽略移动设备)。用于这些凭据的代码是不同的。

    因此,如果您使用带有为 Oauth2 安装的应用程序设计的代码的服务帐户密钥文件。您通常会收到"Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested"

    我通常用于使用服务帐户进行委派的代码如下。它看起来与您的相似,因此我倾向于同意您使用的是服务帐户代码。这对我来说意味着您可能使用了错误的密钥文件。我会仔细检查。打开它应该说"type": "service_account"

    // Load the Service account credentials and define the scope of its access.
    var credential = GoogleCredential.FromFile(PathToServiceAccountKeyFile)
                .CreateWithUser("user@mydomain.com")
                .CreateScoped(new[] {DriveService.ScopeConstants.Drive});
    

    我的建议是现在仔细检查并确保您使用的服务帐户密钥文件来自 google cloud console,该文件由您域上的用户创建,并且您配置了 domain wide deligation 并添加了 admin sdk 范围以记住必须设置管理员的 OAuth 范围,以及配置授权用户。

    【讨论】:

    • 感谢你的回答!抱歉,命名有点混乱,但这是我要委派的用户的电子邮件地址,这就是我如此困惑的原因!如前所述,我以几乎相同的方式使用服务帐户设置了驱动器 api,但这个却收到了该错误消息
    • 真的,我会仔细检查您是否使用了正确的凭据。
    • 哇,也非常感谢更新的答案!我确实发现了我的问题,结果发现目录 api 不在 g 套件管理 api 访问中。这是因为这个项目的设计方式是我需要能够使用我自己的个人凭据来访问目录 api,做我想做的事情,然后使用与驱动器 api 配对的服务帐户进行更改我需要。唯一的问题是我需要弄清楚如何能够做到所有这些并在可能的情况下在个人帐户/服务帐户之间切换哈哈:)
    • 两种不同的凭证和两种不同的服务。应该做的伎俩。
    • 正是我的想法!再次感谢您的帮助。甚至在几年前,我就看到您提出了大多数 google api 问题,我真的很感激。
    猜你喜欢
    • 1970-01-01
    • 2020-04-30
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-04
    • 2015-02-01
    • 2019-08-14
    • 2021-04-10
    相关资源
    最近更新 更多