2015-02-16 1 views
0

Исходя из этого предварительного вопроса: where can i find ServiceAccountCredentialПочему ServiceAccountCredential терпит неудачу с недопустимыми учетными данными?

Я создал свой собственный счет службы, скачал .p12 ключ, включено хранилище.

Но я все еще получаю эту ошибку:

Unhandled Exception: Google.GoogleApiException: Google.Apis.Requests.RequestErro 
r 
Invalid Credentials [401] 
Errors [ 
     Message[Invalid Credentials] Location[Authorization - header] Reason[aut 
hError] Domain[global] 
] 

    at Google.Apis.Requests.ClientServiceRequest`1.Execute() in c:\code\google.co 
m\google-api-dotnet-client\default\Tools\Google.Apis.Release\bin\Debug\test\defa 
ult\Src\GoogleApis\Apis\Requests\ClientServiceRequest.cs:line 93 
    at TestDotNet.Program.Main(String[] args) in C:\Users\jeff\rgs\udemy\TestDotN 
et\Program.cs:line 42 

Вот код:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

// Install-Package Google.Apis.Datastore.v1beta2 
using Google.Apis.Auth.OAuth2; 
using Google.Apis.Http; 
using Google.Apis.Services; 
using Google.Apis.Datastore.v1beta2; 
using Google.Apis.Datastore.v1beta2.Data; 
using System.Security.Cryptography.X509Certificates; 

namespace TestDotNet 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var certificate = new X509Certificate2(
       @"surferjeffEasyBates-ce8b875830c2.p12", 
       "notasecret", X509KeyStorageFlags.Exportable); 
      var serviceAccountEmail = "[email protected]account.com"; 
      ServiceAccountCredential credential = new ServiceAccountCredential(
       new ServiceAccountCredential.Initializer(serviceAccountEmail) 
       { 
        Scopes = new[] { DatastoreService.Scope.Datastore } 
       }.FromCertificate(certificate)); 
      var service = new DatastoreService(new BaseClientService.Initializer 
      { 
       ApplicationName = "surferjeffEasyBates", 
       HttpClientInitializer = credential, 
      }); 
      var lookup_body = new LookupRequest() 
      { 
       Keys = new Key[] { new Key() { Path = new KeyPathElement[] { new KeyPathElement() { 
        Id = 1, 
        Kind = "Thing" 
       }}}} 
      }; 
      var lookup = new DatasetsResource.LookupRequest(service, lookup_body, "surferjeff-easybates"); 
      var response = lookup.Execute(); 
      var found = response.Found[0]; 
      var entity = found.Entity; 
     } 
    } 
} 

я получаю ту же ошибку, независимо от того, хорошо ли я на экземпляре Google Compute Engine или моей локальной машине.

ответ

4

Вам просто не хватает области облачного хранилища данных. В дополнение к хранилищу данных SCOPE требуется «userinfo.email»

Если вы действительно хотите запустить внутри GCE, вы можете просто использовать «ComputeCredentials», как показано на рисунке here.

  • забудьте установить хранилищу и UserInfo областей при создании экземпляра

Добавить экземпляр Google Compute Engine и запустить его, следуя инструкциям для запуска экземпляра в Google Compute Engine documentation. В дополнение к идентификатору проекта и имени экземпляра вы также должны указывать как области хранилища данных, так и имя_экземпляра, как показано на рисунке here.

осциллографы линия должна быть следующей:

Scopes = new[] { DatastoreService.Scope.Datastore ,"https://www.googleapis.com/auth/userinfo.email"}