ASP.NET 核心 grpc 客户端:配置 HTTP 授权



按照 https://learn.microsoft.com/fr-fr/aspnet/core/grpc/authn-and-authz?view=aspnetcore-3.0#bearer-token-authentication 的文档,我尝试将我的GRPC客户端配置为自动注入JWT令牌。

private static GrpcChannel CreateAuthenticatedChannel(string address)
{
var _token = "xxx"; //using some hardcoded JWT token for testing
var credentials = CallCredentials.FromInterceptor((context, metadata) =>
{
if (!string.IsNullOrEmpty(_token))
{
metadata.Add("Authorization", $"Bearer {_token}");
}
return Task.CompletedTask;
});
var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions
{
Credentials = ChannelCredentials.Create(ChannelCredentials.Insecure, credentials)
});
return channel;
}

但它在Grpc.Core中出现异常"提供的通道凭据不允许组合"而窒息

System.ArgumentException
HResult=0x80070057
Message=Supplied channel credentials do not allow composition.
Source=Grpc.Core.Api
StackTrace:
at Grpc.Core.Utils.GrpcPreconditions.CheckArgument(Boolean condition, String errorMessage)
at Grpc.Core.ChannelCredentials.CompositeChannelCredentials..ctor(ChannelCredentials channelCredentials, CallCredentials callCredentials)
at Grpc.Core.ChannelCredentials.Create(ChannelCredentials channelCredentials, CallCredentials callCredentials)
at Service2.StartupCommon.CreateAuthenticatedChannel(String address) in xxxService2StartupCommon.cs:line 32

这是什么意思?我应该如何提供HTTP授权标头?

在挖掘C# 的 Grpc 源代码(尤其是 https://github.com/grpc/grpc/blob/master/src/csharp/Grpc.Core.Api/ChannelCredentials.cs(之后,我们可以看到 ChannelCredentials.Insecure 不会覆盖 IsComposable(而 Grpc.Core.Api/SslCredentials.cs 上提供的 SslCredentials 确实覆盖了该设置(

所以我认为作者的目的是防止不安全通道上的凭据,您必须使用new SslCredentials().

所以我尝试在我的本地机器上设置 HTTPS,并且在一些问题之后(即我必须创建一个 ASP.NET Web api 项目并启动它,以便它建议创建一个 HTTPS 证书并将其添加到 Windows 受信任的机构中,或多或少基于 Visual Studio 中的启用 SSL(,一切正常

所以如果有微软 ASP.NET 核心文档的人,请修改你的文档:

// SslCredentials is used here because this channel is using TLS.
// Channels that aren't using TLS should use ChannelCredentials.Insecure instead.
var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions
{
Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
});

这不是真的:您必须使用安全通道才能更改凭据

最新更新