Hi, I am trying to inject a principal in the reque...
# http4k
m
Hi, I am trying to inject a principal in the request context to get it back in one of my handlers, but I am struggling to understand the example in the docs, specifically this one. The latter uses a single location to do everything, but in a real scenario those elements would typically live in separate part of the app, so I am trying to understand what goes with what. Am I right saying that the contests (RequestsContexts) should be unique and shared for the whole app? Also are there any more examples on how to setup/use request contexts? Thank you in advance.
d
it's up to you, but overall that is broadly true. the requestcontexts need to be initialised and then the request context key is injected where you need it into whatever endpoint needs it
m
But the lenses definition seems to be coupled with a specific requestcontexts, correct? any way to decouple them?
d
there is no way of decoupling that particular implementation because of the way that API works. they should both exist in the HTTP layer and not go deeply into your app (because you need the request in order to retreive the vaue
👍 1
a
Here's a real-life example. Step 1: Initialize the
RequestContextKey
and then inject it into all of your routes. Step 2: In a route, use the
RequestContextKey
to extract the principal from the
Request
and then either authorize it there or pass the principal deeper into your service layer Step 3: In this case, I passed the principal into the service layer, and authorized it there In this case, my
RequestContextKey
merely verifies a JWT and returns the hashed email address as the principal. It doesn't always matter if there's a saved user record; I let my service layer care about that.
🙏 1