如何授权服务帐户访问用户云端硬盘帐户?

时间:2018-05-09 01:34:12

标签: c# .net google-drive-api google-api-dotnet-client service-accounts

我正在尝试允许用户与我的网络应用程序共享文件,我的应用程序有一个服务帐户,并且已成功使用G Suite进行配置。

但是,我无法使用以下代码对ServiceAccount上的用户进行身份验证,例如johndoe@gmail.com,以访问其上传的文件:

ServiceAccountCredential serviceAccountCredential = GoogleCredential.FromFile("service_account_secret.json").CreateScoped(DriveServiceScope).CreateWithUser("john_doe@gmail.com").UnderlyingCredential as ServiceAccountCredential;

使用DriveService发出请求时出现以下异常:

  

Google.Apis.Auth.OAuth2.Responses.TokenResponseException:   '错误:“unauthorized_client”,描述:“客户端未经授权   使用这种方法检索访问令牌。“,Uri:”“''

为了授权我的ServiceAccount访问他的文件,johndoe@gmail.com需要做些什么?

1 个答案:

答案 0 :(得分:0)

在Google Developer Console上创建服务帐户时,您选择了错误的类型。代码和凭证文件对于不同类型的凭证是不同的。

您可能已创建浏览器或本机应用凭据

以下是.net的一些spample代码

    /// <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);
        }
    }
}
}

代码摘自serviceaccount.cs