Hi, I've tried creating a middleware like this: ``...
# http4k
r
Hi, I've tried creating a middleware like this:
Copy code
val authorizationMiddleware: Filter = Filter { next ->
    { req: Request ->
        val token = req.header("Authorization")?.removePrefix("Bearer ")
                ?: throw BadRequestException("'Authorization: Bearer' header is missing.")

        // TODO: Perform token validation logic here
        // JWT? what to use validate the token?

        when {
            token.isNotEmpty() -> next(req) // if (tokenIsValid)
            else -> Response(Status.UNAUTHORIZED)
        }
    }
}
How can I use it in my contract routes? Ive been trying to use it like this but no success
Copy code
// GET /users/{id}
        "/users" / idLens meta {
            summary = "Get user details"
            returning(Status.BAD_REQUEST to "Invalid user id", Status.NOT_FOUND to "User not found")
        } bindContract GET to { id ->
                              authorizationMiddleware.then { req ->
                                  getUser(req, id.toIntOrNull())
                              }
        },
bindContract GET to *{* id *-> {* req *->* authorizationMiddleware.then(getUser(req, id.toIntOrNull())) *} }*,
this also didnt work
d
in your contract add the bearer auth as the security
Copy code
routes += "/bearer_auth" meta {
                security = BearerAuthSecurity("foo")
            } bindContract POST to { _ -> Response(OK) }
Also, this: https://www.http4k.org/guide/reference/contracts/
r
Ok and how does that really work? What is "foo" there?
d
There is an API which you can look at - there are several versions of the constructor which take various things. 🙂
a
Basically, the idea is that
BearerAuthSecurity
accepts: • a
lookup: (String) -> T?
to exchange the bearer token for a principal (e.g. userId) or null • a
RequestContextLens<T>
which is where the principal gets injected If you share the
RequestContextLens
with your application logic, you can use it to extract the principal. I don't know if there are better examples, but I briefly go over auth in my video. Start at the "auth" bookmark, and then continue to the "contract" bookmark, which reuses components defined in the "auth" section.

https://www.youtube.com/watch?v=EUvu4LtGH5Iâ–¾

r
Thanks, it made a bit more sense, I just did not understand the
RequestContextLens
and "principal" part. The lookup looks like what I'm looking for
I mean this
Copy code
val requestContexts = RequestContexts()
    val userIdLens = RequestContextKey.required<String>(requestContexts)
Just wanted to add a simple middleware to my routes and now I have to deal with all of this ._.