使用c#.net中配置文件中的参数对Google Cloud PubSub进行身份验证

时间:2017-08-21 22:36:04

标签: google-cloud-platform google-cloud-pubsub

我正在关注this示例,尝试在Windows服务器上的c#.net应用中发布PubSub中的消息。正如预期的那样,它会抛出auth异常:

PublisherClient publisher = PublisherClient.Create();

我的大多数代码库使用各自的服务连接到GCS和BigQuery,如下所示:

private StorageService GetStorageService()
    {
      X509Certificate2 certificate = new X509Certificate2(certificateFile, "notasecret", X509KeyStorageFlags.Exportable);

      ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(serviceAccountEmail)
                {
                  Scopes = new[] { StorageService.Scope.DevstorageFullControl }
                }.FromCertificate(certificate));

      return new StorageService(new BaseClientService.Initializer()
      {
        HttpClientInitializer = credential,
        ApplicationName = projectNumber,
      });

    }

我只是将配置文件中的certificateFile,serviceAccountEmail作为参数传递。对PubSub来说,Auth有没有相同的功能?

1 个答案:

答案 0 :(得分:0)

是的,这是可能的,而且您正在寻找正确的回购样品。我注意到QuickStart目录缺少README.md。我很快就会添加一个。

要使这行代码正常工作:

PublisherClient publisher = PublisherClient.Create();

将环境变量GOOGLE_APPLICATION_CREDENTIALS设置为json服务帐户凭据文件的路径。详细信息在根自述文件的第3步中: https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/master/README.md

如果您的环境要求您手动指定凭据文件的路径,则代码如下所示:

        GoogleCredential googleCredential = null;
        using (var jsonStream = new FileStream(jsonPath, FileMode.Open,
            FileAccess.Read, FileShare.Read))
        {
            googleCredential = GoogleCredential.FromStream(jsonStream)
                .CreateScoped(PublisherClient.DefaultScopes);
        }
        Channel channel = new Channel(PublisherClient.DefaultEndpoint.Host, 
            PublisherClient.DefaultEndpoint.Port, 
            googleCredential.ToChannelCredentials());
        PublisherClient publisher = PublisherClient.Create(channel);

我报告了问题https://github.com/GoogleCloudPlatform/google-cloud-dotnet/issues/1398,以使这项常见任务更简单。