如何在 C# 中使用服务帐户登录到 Google API - 凭据无效

本文关键字:Google 登录 API 无效 服务 | 更新日期: 2023-09-27 17:56:57

我正在疯狂地试图获得一个简单的服务帐户登录以在 C# 中工作,到 Google API 和 Google Analytics。我的公司已经在将数据导入分析,我可以使用他们的查询资源管理器查询信息,但开始使用 .Net 不会有任何进展。我正在使用带有PKI的Google生成的json文件,因为文档说这样的服务帐户是与Googla API进行计算机到计算机通信的正确方式。代码狙击:

public static GoogleCredential _cred;
public static string _exePath;
static void Main(string[] args) {
    _exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase).Replace(@"file:'", "");
    var t = Task.Run(() => Run());
    t.Wait();
}
private static async Task Run() {
    try {
        // Get active credential
        using (var stream = new FileStream(_exePath + "''Default-GASvcAcct-508d097b0bff.json", FileMode.Open, FileAccess.Read)) {
            _cred = GoogleCredential.FromStream(stream);
        }
        if (_cred.IsCreateScopedRequired) {
        _cred.CreateScoped(new string[] { AnalyticsService.Scope.Analytics });
        }
        // Create the service
        AnalyticsService service = new AnalyticsService(
            new BaseClientService.Initializer() {
                HttpClientInitializer = _cred,
            });
        var act1 = service.Management.Accounts.List().Execute(); // blows-up here

这一切都编译得很好,但是当它命中 Execute() 语句时,会抛出一个GoogleApiException错误:

[凭据无效] 位置[授权 - 标头] 原因[身份验证错误] 域[全局]

我错过了什么?

如何在 C# 中使用服务帐户登录到 Google API - 凭据无效

GoogleAnalytics似乎不能使用通用GoogleCredential并将其解释为ServiceAccountCredential(即使它内部承认它实际上是该类型)。因此,您必须以艰难的方式创建一个ServiceAccountCredential。同样不幸的是,GoogleCredential 没有公开凭据的各种属性,因此我不得不构建自己的属性。

我在 http://jsonclassgenerator.codeplex.com/使用JSON C#类生成器使用JSON Kure构建了一个"个人"ServiceAccountCredential对象,该库是Google API(Newtonsoft.Json)的自动部分,检索了服务帐户的下载json文件的基本部分,以使用其电子邮件和私钥属性构造所需的凭据。将真正的ServiceAccountCredential传递给GoogleAnalytics服务构造函数,将导致成功登录,并访问该帐户允许的资源。

下面的工作代码示例:

using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Analytics.v3;
using Newtonsoft.Json;
    .
    .
    .
try
{
    // Get active credential
    string credPath = _exePath + @"'Private-67917519b23f.json";
    var json = File.ReadAllText(credPath);
    var cr = JsonConvert.DeserializeObject<PersonalServiceAccountCred>(json); // "personal" service account credential
    // Create an explicit ServiceAccountCredential credential
    var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.ClientEmail)
    {
        Scopes = new[] {
            AnalyticsService.Scope.AnalyticsManageUsersReadonly,
            AnalyticsService.Scope.AnalyticsReadonly
        }
    }.FromPrivateKey(cr.PrivateKey));
    // Create the service
    AnalyticsService service = new AnalyticsService(
        new BaseClientService.Initializer()
        {
            HttpClientInitializer = xCred,
        }
    );
    // some calls to Google API
    var act1 = service.Management.Accounts.List().Execute();
    var actSum = service.Management.AccountSummaries.List().Execute();
    var resp1 = service.Management.Profiles.List(actSum.Items[0].Id, actSum.Items[0].WebProperties[0].Id).Execute();

有些人可能想知道带有 PKI(私钥)的 Google 生成的服务帐户凭据是什么样的。从 Google API 管理器(IAM 和管理员)https://console.developers.google.com/iam-admin/projects,选择适当的项目(您至少有一个项目)。现在,选择"服务帐户"(从左侧导航链接)和屏幕顶部的"创建服务帐户"。填写名称,设置"提供新的私钥"复选框,然后单击"创建"。谷歌将导致自动下载一个JSON文件,如下所示:

{
  "type": "service_account",
  "project_id": "atomic-acrobat-135",
  "private_key_id": "508d097b0bff9e90b8d545f984888b0ef31",
  "private_key": "-----BEGIN PRIVATE KEY-----'nMIIE...o/0='n-----END PRIVATE KEY-----'n",
  "client_email": "google-analytics@atomic-acrobat-135.iam.gserviceaccount.com",
  "client_id": "1123573016559832",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://accounts.google.com/o/oauth2/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/google-analytics%40atomic-acrobat-135923.iam.gserviceaccount.com"
}

发生无效凭据错误是因为您指定的范围实际上并未随凭据一起发送。我犯了同样的错误,只有在调试后才意识到,并且在CreateScoped调用后仍然在凭据上看到 0 个作用域。

GoogleCredential是不可变的,因此CreateScoped创建具有指定作用域集的新实例。

使用作用域结果重新分配您的凭据变量,如下所示,它应该可以工作:

  if (_cred.IsCreateScopedRequired) {
    _cred = _cred.CreateScoped(AnalyticsService.Scope.Analytics);
  }

公认的答案之所以有效,是因为它以更困难的方式实现了同样的事情。

在2020年,您不需要执行所有这些操作,GoogleCredential可以正常工作。问题中的代码看起来正确,除了一行:

credentials.CreateScoped(new string[] { DriveService.Scope.Drive });

CreateScoped 方法返回凭据的副本。如果您将其重新分配给自身,它就可以工作。

为了完整起见,这是我的测试代码,运行良好:

using (var stream =
            new FileStream("drive-credentials.json", FileMode.Open, FileAccess.Read))
        {                
            var credentials = GoogleCredential.FromStream(stream);
            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(new string[] { DriveService.Scope.Drive });
            }

            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentials,
                ApplicationName = "application name",                    
            });
            FilesResource.ListRequest listRequest = service.Files.List();
            listRequest.PageSize = 10;
            listRequest.Fields = "nextPageToken, files(id, name)";
            // List files.
            IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
                .Files;
        }

对于 2020,调用如下:

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using Google.Apis.Services;
using Google.Apis.Auth.OAuth2;
using System.IO;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
namespace SistemasInfinitos.Controllers.Google.Apis.Sample.MVC4
{
    public class SpreadsheetseController : Controller
    { 
        public ActionResult IndexAPI()
        {
            //accede a las credenciales
            var stream = new FileStream(Server.MapPath("~/quickstart2-9aaf.json"),
                FileMode.Open
               // FileAccess.Read//SOLO LECTURA
                );
            //abre las credenciales
            var credentials = GoogleCredential.FromStream(stream);
            //virifica las credenciales
            if (credentials.IsCreateScopedRequired)
            {
                credentials = credentials.CreateScoped(new string[] { SheetsService.Scope.Spreadsheets });
            }
            ///inicializa la api
        var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credentials,
                ApplicationName = "SistemasInfinitos",
            });
            // Define los parametros.  
            String spreadsheetId = "1MKxeqXV5UEMXU2yBe_xi0nwjooLhNN6Vk";
            String range = "Sheet1";
            SpreadsheetsResource.ValuesResource.GetRequest request =service.Spreadsheets.Values.Get(spreadsheetId, range);
            // imprime   
            ValueRange response = request.Execute();
            IList<IList<Object>> values = response.Values;
            ViewBag.List = values;
            return View();
        }
    }
}

和查看

@{
    ViewBag.Title = "IndexAPI";
}
<div class="col-md-6">
    <h3>Read Data From Google Live sheet</h3>
    <table class="table" id="customers">
        <thead>
            <tr>
                <th>
                    id
                </th>
                <th>
                    Name
                </th>
            </tr>
        </thead>
        <tbody>
            @{
                foreach (var item in ViewBag.List)
                {
                    <tr>
                        <td>@item[0]</td>
                        <td>@item[1]</td>
                    </tr>
                }
            }
        </tbody>
    </table>
</div>

另一种选择是使用 GoogleCredential.GetApplicationDefault() .我相信这是目前(2018年10月)推荐的方法。下面是一些 F#,但在 C# 模语法中或多或少是相同的:

let projectId = "<your Google Cloud project ID...>"
let creds =
  GoogleCredential.GetApplicationDefault()
    .CreateScoped(["https://www.googleapis.com/auth/cloud-platform"])
use service =
  new CloudBuildService(
    BaseClientService.Initializer(HttpClientInitializer=creds))
let foo = service.Projects.Builds.List(projectId).Execute()

现在,只需确保将GOOGLE_APPLICATION_CREDENTIALS设置为指向具有凭据 JSON 文件的文件,例如。 GOOGLE_APPLICATION_CREDENTIALS=creds.json dotnet run .

如果您在尝试确定如何创建ServiceAccountCredential时到达此处,而不直接使用密钥文件,您可能有兴趣知道以下方法将起作用(有时):

GoogleCredential credential = GoogleCredential.GetApplicationDefault();
ServiceAccountCredential serviceAccountCredential = 
    credential.UnderlyingCredential as ServiceAccountCredential;