I am implementing a Grpc server in Elixir and have some questions about headers. I believe I can retrieve the headers from the stream data in the request implementation. This looks straight-forward. I have not been able to find a way to send headers using the Stub client. I am planning on having the client send per request auth header and would like to use the Stub client for testing the server implementation, but can’t figure out how to pass headers.
1 Like
Looks like the the stub has a way to pass headers. This does not appear to be documented. Had to do a bit of spelunking in the code.
committed 08:08AM - 24 Dec 19 UTC
* Add mechanism to set headers in Stub.connect/3
This patch provides a generi… c way to set headers that will be attached
to each request from this `channel` by re-using
append_custom_metadata/2.
The use case is to provide a location for setting authorization headers
that does not require manually adding it to each Stub fn call.
With this change, headers can be set as:
```
channel = Stub.connect(host, port, headers: [{"authorization", "Bearer TOKEN"}])
```
On the receiving server side they can be accessed using existing getter
function. For the authorization example, this can be done in an
Interceptor:
```elixir
defmodule Authenticator do
def init(_), do: []
def call(req, stream, next, opts) do
with headers when is_map(headers) <- GRPC.Stream.get_headers(stream),
token when not is_nil(token) <- Map.get(headers, "authorization") do
.... # use token
.... # if authenticated
next.(req, stream)
end
end
end
```
Adds two tests, one to verify on client side that headers can be set and
accessible, a second test is for integration to verify the roundtrip of
a header from client to server, then encode the header into a GRPC
message response for test verification.
* Avoid compilation warning about uniform_real/0 missing on Elixir 1.9
Co-authored-by: Tony Han <h.bing612@gmail.com>
1 Like