【问题标题】:trying to Azure AD authentication with gRPC-Web using protobuf-net尝试使用 protobuf-net 通过 gRPC-Web 进行 Azure AD 身份验证
【发布时间】:2020-10-22 00:28:43
【问题描述】:

我正在尝试在 blazor webassembly 应用程序中使用 gRPC-Web 进行 Azure AD 身份验证。我正在使用 protobuf-net 来帮助我进行序列化。我不确定如何传递令牌以让服务器端识别它。这就是我所拥有的:

var headers = new Metadata
               {
                 { "Authorization", $"Bearer {Token}" }
               };

并且,我将它作为我想要使用的方法中的参数发送

var result = await Client.CreateCustomer(this.customer, headers);

这是注入服务的方式:

builder.Services.AddTransient(services =>
        {
            var httpClient = new HttpClient(new GrpcWebHandler(GrpcWebMode.GrpcWeb, new HttpClientHandler()));
            var channel = Grpc.Net.Client.GrpcChannel.ForAddress("****", new GrpcChannelOptions { HttpClient = httpClient });
            return channel.CreateGrpcService<Application.Services.ICustomerService<ServerCallContext>>();
        });

这是服务的发布方式:

endpoints.MapGrpcService<CustomerService>().RequireAuthorization().EnableGrpcWeb()

而且,这是实现:

public class CustomerService : ICustomerService<ServerCallContext>
{
    [Authorize]
    public async ValueTask<Customer> CreateCustomer(Customer customerDTO, ServerCallContext context) 
    {****}
}

我得到的错误是无法从“Grpc.Core.Metadata”转换为“Grpc.Core.ServerCallContext”,这很明显。

我发现的参考使用元数据,但我应该使用 ServerCallContext https://docs.microsoft.com/en-us/dotnet/architecture/grpc-for-wcf-developers/metadata 所以我错过了什么,我做错了什么,如何使用 protobuf-net 正确使用两者?

【问题讨论】:

    标签: asp.net-core protobuf-net blazor-webassembly protobuf-net.grpc


    【解决方案1】:

    看起来这里的问题是您在方法签名中使用了ServerCallContext;底层 gRPC 核心具有单独的客户端/服务器上下文 API,但这不适用于不可知的接口,因此,protobuf-net.Grpc 统一这两个 API,通过CallContext。所以:而不是:

    async ValueTask<Customer> CreateCustomer(Customer customerDTO, ServerCallContext context)
    

    对于签名,请考虑:

    async ValueTask<Customer> CreateCustomer(Customer customerDTO, CallContext context)
    

    async ValueTask<Customer> CreateCustomer(Customer customerDTO, CallContext context = default)
    

    CallContext API 以单一方式公开常见的服务器端和客户端 API(标头、取消等),或者您可以使用(例如)context.ServerCallContext 获取特定于服务器的 API,如果需要(如果在客户端上下文中使用,这将引发异常)。对于客户端使用,CallContext 可以从 CallOptions 构造,这是核心 gRPC 客户端 API,例如:

    var result = await service.CreateCustomer(customer, new CallOptions(headers));
    

    接受允许直接从Metadata / CancellationToken 等创建CallContext 的想法(允许var result = await service.CreateCustomer(customer, headers);) - 但它似乎没有必不可少的

    【讨论】:

    • @paburgos 不客气;如果它回答了您的问题,请考虑按下绿色勾号图标
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多