Hi, I’m trying to consume an API that requires OAu...
# http4k
l
Hi, I’m trying to consume an API that requires OAuth. So, I’ve been following the OAuth reference. Assuming I configured the relevant
oAuthPersistence
and
oAuthProvider
, I got the following:
Copy code
val clientCall = { request ->
    oAuthPersistence.retrieveToken(request)
        ?.let { accessToken ->
            client(
                Request(GET, "/")
                    .header("Authorization", "Bearer ${accessToken.value}")
            )
        }
        ?: Response(Status.UNAUTHORIZED)
}

val app = routes(
    "/oauth" bind routes(
        "/" bind GET to oAuthProvider.authFilter.then(clientCall),
        "/callback" bind GET to oAuthProvider.callback
    )
)
It’s working fine, but it feels that getting the access token to include it in the client API call is more complicated than expected. So I wonder whether there’s a better way of doing it. Any thoughts?
I introduced a filter so that client calls don’t need to worry about auth:
Copy code
val bearerAuth = Filter { next ->
    { request ->
        oAuthPersistence.retrieveToken(request)
            ?.let { accessToken ->
                next(request.header("Authorization", "Bearer ${accessToken.value}"))
            }
            ?: Response(UNAUTHORIZED)
    }
}
But I wonder if the
OAuthRedirectionFilter
defined by the
OAuthProvider
could append the token to the request when it finds a token: https://github.com/http4k/http4k/blob/78e5b3d7a92afe2e7dd1d01786191764befddb2f/htt[…]h/src/main/kotlin/org/http4k/security/OAuthRedirectionFilter.kt