roby
05/27/2023, 8:22 PMval 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
// 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())
}
},
roby
05/27/2023, 8:22 PMbindContract GET to *{* id *-> {* req *->* authorizationMiddleware.then(getUser(req, id.toIntOrNull())) *} }*,
this also didnt workdave
05/27/2023, 8:33 PMroutes += "/bearer_auth" meta {
security = BearerAuthSecurity("foo")
} bindContract POST to { _ -> Response(OK) }
Also, this: https://www.http4k.org/guide/reference/contracts/roby
05/27/2023, 8:57 PMdave
05/27/2023, 9:05 PMAndrew O'Hara
05/28/2023, 2:22 AMBearerAuthSecurity
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.
roby
05/28/2023, 7:39 PMRequestContextLens
and "principal" part. The lookup looks like what I'm looking forroby
05/28/2023, 7:48 PMval requestContexts = RequestContexts()
val userIdLens = RequestContextKey.required<String>(requestContexts)
roby
05/28/2023, 7:55 PM