ASP.NET Core 6: Here is the best way to pass a JWT in the headers of a gRPC client
Dear developers who love gRPC, I have something here that you might like. You’ve probably wondered how to pass (cleanly and non-repetitively) headers in a gRPC client? I found a solution that doesn’t involve any Interceptor, because with the latter it doesn’t work! In this article I will show you an example by passing a JWT in the headers.
A bit of context
In the introduction I mentioned the fact that it was not possible, in a gRPC interceptor, to pass headers automatically without having to repeat in each method of a gRPC client. I will explain myself: if you thought of using the context.CallOptions.Headers object in an interceptor, it will not work because quite simply the Headers object is not initialized and therefore it will be null. For more details you can consult the following link which explains the problem and its solution with an alternative for a gRPC client that does not use the HttpClient factory of .NET 6: https://github.com/grpc/grpc/issues /15272.
In the next section I will show you how to do the same with a gRPC typed client in .NET 6.
I will show you how to avoid the following which uses a TokenService into a repository:
As you can see, if you have several methods, you will have to acquire a token in each methods, which is repetitive. .NET 6 allows you to attach a delegate (which can be asynchronous) to a gRPC type client which allows you to automatically manipulate the headers (among other things) of each call made to the gRPC server and this is done through the gRPC client options. The CallOptionsAction property makes it possible to attach, as I mentioned, a delegate which will make it possible to interact with the CallOptions object which contains a Headers property. In the delegate just call the TokenService as follows:
The delegate will be invoked on every call from a gRPC endpoint so there is no risk that the JWT will be the same on every call. For your information the TokenService, for the needs of the demo looks like this, and you can completely contextualize the generation of a JWT from the current user by calling IHttpContextAccessor:
Here’s a little demo to show you that I’m not lying 🙂
Beautiful isn’t it ? 😉