如何使用服务器密钥在 Google 电子表格 Api V4 中进行身份验证

How to authenticate in Google Spreadsheet Api V4 with Server Key

我正在尝试像这样使用 google 带有服务器密钥(在 console.cloud.google.com 中创建)的电子表格

var service = new SheetsService(new BaseClientService.Initializer
    {
        ApplicationName = "myappname",
        ApiKey = "mykey"
    });

但是在第一次请求后我收到了一个错误

Message[The request does not have valid authentication credentials.]

那么如何仅使用服务器密钥进行身份验证?

使用服务帐户凭据从服务器使用 api 可能更好(当然如果可能的话)?

试试这个 code written by Владимир Рак:

var certificate = new X509Certificate2("pathTo***.p12", "notasecret", X509KeyStorageFlags.Exportable);
        var serviceAccountEmail = "********-*********@developer.gserviceaccount.com";
        var userAccountEmail = "******@gmail.com";
        ServiceAccountCredential credential = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(serviceAccountEmail)
                   {
                       Scopes = new[] { DriveService.Scope.Drive },
                       User = userAccountEmail

}.FromCertificate(certificate)); // Create the service. var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "*****", });