Search code examples
http-headersauthorizationktorktor-client

Ktor Client builder not showing authentication headers in request


I'm using the Ktor Client dsl to add the auth plugin like this:

import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import io.ktor.client.plugins.auth.*
import io.ktor.client.plugins.auth.providers.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.coroutines.runBlocking``

val client = HttpClient(OkHttp) {
    install(Auth) {
        basic {
            credentials {
                BasicAuthCredentials(email, token)
            }
        }
    }
    install(Logging) {
        logger = Logger.DEFAULT
        level = LogLevel.ALL
    }
}

But the logger does not show any Basic authentication header:

15:47:14.589 [DefaultDispatcher-worker-3] INFO io.ktor.client.HttpClient - REQUEST: https://example.url.net/api
METHOD: HttpMethod(value=GET)
COMMON HEADERS
-> Accept: */*
-> Accept-Charset: UTF-8
// >>> SHOULD BE HERE <<<
CONTENT HEADERS
-> Content-Length: 0
BODY Content-Type: null
BODY START

When adding the headers for a GET through this other method now works:

fun search() {
    runBlocking {
        val response: HttpResponse = client.get(url) {
            headers {
                append(HttpHeaders.Authorization, "Basic $auth")
            }
        }
        println(response.bodyAsText())
    }
}

The request has all the correct headers:

15:49:47.407 [DefaultDispatcher-worker-3] INFO io.ktor.client.HttpClient - REQUEST: https://example.url.net/api
METHOD: HttpMethod(value=GET)
COMMON HEADERS
-> Accept: */*
-> Accept-Charset: UTF-8
-> Authorization: Basic fwouwneg34g38gngwg // HERE
CONTENT HEADERS
-> Content-Length: 0
BODY Content-Type: null
BODY START

Note: I'm using this dependencies in Kotlin Multiplatform for desktop jvm:

implementation("io.ktor:ktor-client-core:2.1.0")
implementation("io.ktor:ktor-client-okhttp:2.1.0")
implementation("io.ktor:ktor-client-auth:2.1.0")
implementation("io.ktor:ktor-client-logging:2.1.0")
implementation("ch.qos.logback:logback-classic:1.3.0-beta0")

Solution

  • By default, the Authorization header isn't sent for each request but only when a server responds with the 401 status code and the WWW-Authenticate header. To send the Authorization header for each request you can call the sendWithoutRequest method with the { true } lambda.

    install(Auth) {
        basic {
            sendWithoutRequest { true }
        }
    }
    

    For more information about Basic authentication in Ktor please read the documentation.