Net Core gRPC - 07. 身份验证与授权

Net Core gRPC 系列

1. gRPC使用HTTP标头

在 .NET gRPC 客户端中,可通过 Metadata 集合与调用一起发送。 Metadata 集合中的条目以 HTTP 标头的形式与 gRPC 调用一起发送。

客户端发送header
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//IPC进程内部调用发送header 整体设置 不需要每次调用都设置
var credentials = CallCredentials.FromInterceptor((context, metadata) =>
{
if (!string.IsNullOrEmpty(_token))
{
metadata.Add("Authorization", $"Bearer {_token}");
}
return Task.CompletedTask;
});
var channel = new ColaGrpcHelper(new ColaWindowsGrpc()).CreateChannel("https://localhost:5005",config,null,credentials);
var invoker =
channel.Intercept(new ClientGrpcInterceptor(builder.Services.BuildServiceProvider().GetService<IColaLogs>()!,
config));
var client = new Greeter.GreeterClient(invoker);

//IPC进程内部每次调用发送header
var headers = new Metadata();
headers.Add("customHeader","odin-custom-header");
var helloReply = client.SayHelloAsync(new HelloRequest
{
Name = "odin-sam"
},headers);
var resultOnce = await helloReply;
Console.WriteLine(resultOnce.Message);

// Ioc注入 发送调用
builder.Services
.AddGrpcClient<Greeter.GreeterClient>(o =>
{
o.Address = new Uri("https://localhost:5005");
o.Interceptors.Add(new ClientGrpcInterceptor(builder.Services.BuildServiceProvider().GetService<IColaLogs>()!,
config));
})
.AddCallCredentials((context, metadata) =>
{
if (!string.IsNullOrEmpty(_token))
{
metadata.Add("Authorization", $"odinsam Bearer {_token}");
}
return Task.CompletedTask;
})
.ConfigureChannel(options =>
{
options.CreateGrpcClientChannelOptions(config);
});
var client = builder.Services.BuildServiceProvider().GetService<Greeter.GreeterClient>();
服务端获取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
foreach (var item in context.RequestHeaders)
{
Console.WriteLine($"item key:{item.Key} item value:{item.Value}");
}
return Task.FromResult(new HelloReply
{
Message = "Hello webApi " + request.Name
});
}
//获取结果
//item key:user-agent item value:grpc-dotnet/2.46.0 (.NET 6.0.15; CLR 6.0.15; net6.0; windows; x64)
//item key:authorization item value:odinsam Bearer asdf
//item key:traceparent item value:00-b9e81c4197481d2dc009901da83ec3a3-308132d606c66f4b-00
//item key:customheader item value:odin-custom-header