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

Authenticate for Google Cloud PubSub using parameters from a config file in c#.net

我正在关注 this 示例,试图从 windows 服务器上的 c#.net 应用程序在 PubSub 中发布消息。正如预期的那样,它会抛出身份验证异常:

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?

是的,这是可能的,而且您正在寻找正确的样本库。我注意到 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 以简化这项常见任务。