https://kotlinlang.org logo
#ktor
Title
# ktor
l

Lucas

08/12/2022, 3:34 AM
Im using ktor client to call this API which needs basic authorization. My application has credentials for several users of this API, and i need to change the auth header for each different user. Initially i thought about using the same HttpClient and change the header on each request, but i didnt find a way to do so (using the basic auth plugin). Should i be using different clients for each user? I feel like this could be expensive and if i could reuse the clients it would be much better. Or should i just be setting the header manually on each request, and stop using the basic auth plugin?
a

Aleksei Tirman [JB]

08/12/2022, 4:32 PM
I suggest sending the
Authorization
header manually. Here is an example:
Copy code
suspend fun main() {
    val client = HttpClient(Apache) {}

    val r = client.get("<https://httpbin.org/basic-auth/john/123>") {
        header(HttpHeaders.Authorization, basicAuthHeader("john", "123"))
    }

    println(r.bodyAsText())
}

fun basicAuthHeader(name: String, password: String): String {
    val authString = "$name:$password"
    val authBuf = authString.toByteArray(Charsets.UTF_8).encodeBase64()

    return "Basic $authBuf"
}
l

Lucas

08/12/2022, 7:56 PM
But i definitely should be reusing the client then, correct?
h

hfhbd

08/12/2022, 7:58 PM
you don't have to, but yeah I would reuse it
239 Views