如何在C#中验证Hangouts Chat webhook令牌



我正在用ASP开发一个非常简单的聊天机器人。NET webhook来处理响应。我在发送或接收消息时没有遇到任何问题,但我有点拘泥于验证Authorization标头中的Bearer令牌,以验证传入请求是否来自谷歌。

我已经包括了谷歌。Apis。Auth API版本1.55。它具有进行此验证的功能。当然,文档中没有给出。NET的例子,但据我所知,它应该是这样的:

try
{
string token = "token here";
SignedTokenVerificationOptions stvo = new SignedTokenVerificationOptions()
{ 
TrustedAudiences = { "my project id" },
TrustedIssuers = { "chat@system.gserviceaccount.com" },
CertificatesUrl = "https://www.googleapis.com/service_accounts/v1/metadata/x509/chat@system.gserviceaccount.com"
};
JsonWebSignature.Payload r = await JsonWebSignature.VerifySignedTokenAsync(token, stvo);
return true;
}
catch (InvalidJwtException)
{
return false;
}

我的问题是,我从API内部得到一个异常,看起来它正在处理来自谷歌的证书。我认为我对这一点没有太大的影响力!

System.ArgumentNullException: Value cannot be null.
Parameter name: source
at System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)
at Google.Apis.Auth.SignedTokenVerification.CertificateCacheBase.<GetCertificatesAsync>d__5.MoveNext() in C:Apiary2021-09-08.15-52-39SrcSupportGoogle.Apis.AuthSignedTokenVerification.cs:line 246
at Google.Apis.Auth.SignedTokenVerification.<GetCertificatesAsync>d__6.MoveNext() in C:Apiary2021-09-08.15-52-39SrcSupportGoogle.Apis.AuthSignedTokenVerification.cs:line 203
at Google.Apis.Auth.SignedTokenVerification.<VerifyRS256TokenAsync>d__4`2.MoveNext() in C:Apiary2021-09-08.15-52-39SrcSupportGoogle.Apis.AuthSignedTokenVerification.cs:line 110
at Google.Apis.Auth.SignedTokenVerification.<VerifySignedTokenAsync>d__3`2.MoveNext() in C:Apiary2021-09-08.15-52-39SrcSupportGoogle.Apis.AuthSignedTokenVerification.cs:line 102
at Google.Apis.Auth.JsonWebSignature.<VerifySignedTokenAsync>d__1`1.MoveNext() in C:Apiary2021-09-08.15-52-39SrcSupportGoogle.Apis.AuthJsonWebSignature.cs:line 61
at GroupHandler.<>c__DisplayClass0_0.<<ProcessRequest>b__0>d.MoveNext() in D:IISSitesTestGoogleBotVerify.ashx:line 31

这是正确的方法吗?还是我错过了一些显而易见的东西?:(Joel

它应该是标准的服务帐户授权。

你需要谷歌。Apis。Auth和Google。Apis。HangoutsChat.v1包。

public class HangoutsAuth
{
public static string[] scopes =  { "https://www.googleapis.com/auth/chat.bot" };
private static GoogleCredential GetCredential(string pathToServiceAccountKeyFile, string[] scopes)
{
// Load the Service account credentials and define the scope of its access.
return GoogleCredential.FromFile(pathToServiceAccountKeyFile)
.CreateScoped(scopes);
}    

}

用就可以了

var service = HangoutsAuth.GetService(PathToKeyFile,  { "https://www.googleapis.com/auth/chat.bot" });
var response = await service.Spaces.Messages.Create(body, "spaces/AAAA2CiqVDM").ExecuteAsync();

最新更新