遵循https://learn.microsoft.com/fr-fr/aspnet/core/grpc/authn-and-authz?view=aspnetcore-3.0#bearer-token-authentication处的文档,我尝试将 GRPC 客户端配置为自动注入(inject) JWT token 。
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 中的异常“提供的 channel 凭据不允许组合”而阻塞
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 (而 Grpc.Core.Api/SslCredentials.cs 中提供的 SslCredentials 会覆盖该设置)
所以我认为作者的目的是防止不安全通道上的凭据,您必须使用new SslCredentials()
。
因此,我尝试在本地计算机上设置 HTTPS,但在出现一些问题之后(即我必须创建一个 ASP.NET Web api 项目并启动它,因此它建议创建一个 HTTPS 证书并将其添加到Windows 受信任的机构,或多或少基于 Enable SSL in Visual Studio ),一切正常
因此,如果有人来自microsoft ASP.NET core文档,请修改您的文档:
// 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)
});
这不是真的:您必须使用安全通道才能更改凭据
关于asp.net-core - ASP.NET Core grpc 客户端 : configuring HTTP authorization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58990213/