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

ASP.NET Core grpc client : configuring HTTP authorization

按照 https://docs.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

中因异常 "Supplied channel credentials do not allow composition" 而窒息
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 xxx\Service2\StartupCommon.cs:line 32

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

在 C# 的 Grpc 源代码中进行一些挖掘之后,尤其是 https://github.com/grpc/grpc/blob/master/src/csharp/Grpc.Core.Api/ChannelCredentials.cs,我们可以看到 ChannelCredentials.Insecure 没有覆盖 IsComposable(而 SslCredentials 在 Grpc.Core 中可用。Api/SslCredentials.cs 确实会覆盖该设置)

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

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

因此,如果有人来自微软 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)
});

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