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"
}