为什么ServiceAccountCredential失败并且凭据无效?

时间:2015-02-16 18:37:06

标签: c# google-compute-engine google-api-dotnet-client

基于此前一个问题: where can i find 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 = "340967622364-pls45ap9lu4u6ivtivpus62tm8sgtodg@developer.gserviceaccount.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;
        }
    }
}

无论我是在谷歌计算引擎实例还是我的本地计算机上运行,​​都会收到同样的错误。

1 个答案:

答案 0 :(得分:4)

您只是缺少Cloud Datastore的必需范围。除了数据存储区SCOPE之外,它还需要' userinfo.email'

如果你真的想在GCE中运行,你可以简单地使用" ComputeCredentials"如图所示here

  • 记得在创建实例时设置数据存储区和userinfo范围

添加Google Compute Engine实例并按照Google Compute Engine documentation中启动实例的说明启动它。除项目ID和实例名称外,还必须同时指定数据存储区和用户标识范围here

范围行应如下:

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