将自定义凭据与 Stackdriver Logging API C# 客户端库一起使用

Using custom credentials with Stackdriver Logging API C# Client Library

我想使用 GoogleCredential 对象(或类似对象)以使用一些自定义凭据创建 Stackdriver 日志记录客户端对象(LoggingServiceV2Client class 的实例)而不是默认的应用程序凭证。

我看不到 LoggingServiceV2Client.Create 方法的适当重载,但该方法的文档字符串指出:

Synchronously creates a Google.Cloud.Logging.V2.LoggingServiceV2Client, applying defaults for all unspecified settings, and creating a channel connecting to the given endpoint with application default credentials where necessary. See the example for how to use custom credentials.

这表明它可能以某种方式存在?

我无法在任何地方的文档中找到自定义凭据示例。我看到的唯一示例(例如 this)仅读取来自 GOOGLE_APPLICATION_CREDENTIALS 环境变量的 default 应用程序凭据,我希望避免

有可能,但远非显而易见。

将这两个 using 语句添加到 .cs 的顶部:

using Google.Apis.Auth.OAuth2;
using Grpc.Auth;

然后像这样实例化客户端:

var credential = GoogleCredential.FromFile(jsonPath)
    .CreateScoped(LoggingServiceV2Client.DefaultScopes);
var channel = new Grpc.Core.Channel(
    LoggingServiceV2Client.DefaultEndpoint.ToString(),
    credential.ToChannelCredentials());
var client = LoggingServiceV2Client.Create(channel);

我已经感谢@Jeffrey Rennie。就我而言,我使用的是 Cloud Text-to-Speech 并且我必须使用以下代码:

使用:

using Google.Apis.Auth.OAuth2;
using Google.Cloud.TextToSpeech.V1;
using Grpc.Auth;

代码:

// Setting up credentials
string jsonPath = @"D:\my-test-project-0078ca7c0f8c.json";
var credential = GoogleCredential.FromFile(jsonPath).CreateScoped(TextToSpeechClient.DefaultScopes);
var channel = new Grpc.Core.Channel(TextToSpeechClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());

// Instantiate a client
TextToSpeechClient client = TextToSpeechClient.Create(channel);

// Perform the Text-to-Speech request, passing the text input with the selected voice parameters and audio file type 
var response = client.SynthesizeSpeech(new SynthesizeSpeechRequest
{
    Input = new SynthesisInput() { Text = "My test sentence" },
    Voice = new VoiceSelectionParams() { LanguageCode = "en-US", SsmlGender = SsmlVoiceGender.Male },
    AudioConfig = new AudioConfig { AudioEncoding = AudioEncoding.Mp3 };
});

已安装的 NuGet 包:
Google.Cloud.TextToSpeech.V1 -Pre
Google.Apis.Auth

使用 Google.Cloud.Logging.V2 的其他解决方案对我不起作用 - 版本:3.4.0,因为这一行:

var client = LoggingServiceV2Client.Create(channel);

在 3.4.0 版本中,没有将通道作为参数的构造函数。

所以我检查了 google 文档:LoggingServiceV2Client Create(),它有这个小注释:

To specify custom credentials or other settings, use LoggingServiceV2ClientBuilder

所以这是我使用这种方法的工作代码:

var credential = GoogleCredential.FromFile(jsonPath).CreateScoped(LoggingServiceV2Client.DefaultScopes);

var client = new LoggingServiceV2ClientBuilder { ChannelCredentials = credential.ToChannelCredentials() }.Build();