.NET Google DRIVE API客户端库-客户端未经授权使用此方法检索访问令牌

时间:2018-10-30 13:36:33

标签: google-api google-drive-api google-api-dotnet-client google-drive-team-drive

我正在使用.NET谷歌客户端库中的Google DRIVE API,并希望模拟服务帐户中的用户。我已经阅读过许多其他用户面临相同的问题,但没有一个修复程序适合我。下面是详细信息。

  1. 创建服务帐户并启用域范围的委派(现已超过3小时)。
  2. 下载* .p12文件并记下秘密密码
  3. 添加了具有服务帐户客户端ID的权限驱动器作用域
  4. 使用以下代码创建服务并从Google云端硬盘上传/获取数据

代码

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select ng-model="selectedName" ng-options="x for x in names" style="width: 180px">
</select>
</div>

<p>This example shows how to fill a dropdown list using the ng-options directive.</p>

</body>

在Request_ProgressChanged事件中发送的第一个数据被卡住时,我遇到了错误。

执行google API方法时,它会抛出错误

  

错误:“ unauthorized_client”,说明:“客户端未经授权   使用此方法检索访问令牌。“,Uri:”“

我已经检查了许多启用了DWD的论坛以及aaded应用程序范围。... 任何人有任何想法请帮助,

1 个答案:

答案 0 :(得分:0)

有几种访问Google API的方法。使用Oauth2和使用服务帐户。

创建的客户端以及用于服务帐户的代码不同于为浏览器应用程序创建的客户端以及用于对其进行身份验证的代码。如果您转到Google开发者控制台并创建浏览器客户端,则无法与此客户端一起使用服务帐户代码。具有浏览器clinet ID的服务帐户代码也是如此。

  

错误:“ unauthorized_client”,说明:“未授权客户端使用此方法检索访问令牌。”,Uri:“”

基本上意味着您使用的客户端不是您使用的代码的正确类型。

返回Google Developer Console创建服务帐户,下载服务帐户.json文件

ServiceAccount.cs

using Google.Apis.Drive.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using System;
using System.IO;
using System.Security.Cryptography.X509Certificates;

namespace GoogleSamplecSharpSample.Drivev3.Auth
{

    public static class ServiceAccountExample
    {

        /// <summary>
        /// Authenticating to Google using a Service account
        /// Documentation: https://developers.google.com/accounts/docs/OAuth2#serviceaccount
        /// </summary>
        /// <param name="serviceAccountEmail">From Google Developer console https://console.developers.google.com</param>
        /// <param name="serviceAccountCredentialFilePath">Location of the .p12 or Json Service account key file downloaded from Google Developer console https://console.developers.google.com</param>
        /// <returns>AnalyticsService used to make requests against the Analytics API</returns>
        public static DriveService AuthenticateServiceAccount(string serviceAccountEmail, string serviceAccountCredentialFilePath, string[] scopes)
        {
            try
            {
                if (string.IsNullOrEmpty(serviceAccountCredentialFilePath))
                    throw new Exception("Path to the service account credentials file is required.");
                if (!File.Exists(serviceAccountCredentialFilePath))
                    throw new Exception("The service account credentials file does not exist at: " + serviceAccountCredentialFilePath);
                if (string.IsNullOrEmpty(serviceAccountEmail))
                    throw new Exception("ServiceAccountEmail is required.");                

                // For Json file
                if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".json")
                {
                    GoogleCredential credential;
                    using (var stream = new FileStream(serviceAccountCredentialFilePath, FileMode.Open, FileAccess.Read))
                    {
                        credential = GoogleCredential.FromStream(stream)
                             .CreateScoped(scopes);
                    }

                    // Create the  Analytics service.
                    return new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Drive Service account Authentication Sample",
                    });
                }
                else if (Path.GetExtension(serviceAccountCredentialFilePath).ToLower() == ".p12")
                {   // If its a P12 file

                    var certificate = new X509Certificate2(serviceAccountCredentialFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
                    var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
                    {
                        Scopes = scopes
                    }.FromCertificate(certificate));

                    // Create the  Drive service.
                    return new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName = "Drive Authentication Sample",
                    });
                }
                else
                {
                    throw new Exception("Unsupported Service accounts credentials.");
                }

            }
            catch (Exception ex)
            {                
                throw new Exception("CreateServiceAccountDriveFailed", ex);
            }
        }
    }
}

如果仍然无法正常工作,则表明您没有正确配置对服务帐户delegatingauthority的域范围委派