# ktor

Karen Frangulyan

03/15/2022, 11:25 AM
Hey guys, I'm new to ktor and having problems with Auth plugin on mobile. Our backend returns 401 (Unauthorized) without the
header set, as a result the
is not being triggered. I tried to solve this by intercepting the responses and adding that header manually on mobile client, however, token refresh is still not triggered and I don't see that header in http response logs, even though the interceptor code is being executed. Below is the simplified version of my client setup:
Copy code
    install("Fix Unauthorized headers") {
        receivePipeline.intercept(HttpReceivePipeline.Before) { response ->
            println("----------- INTERCEPTING!") // this is printed
    install(Auth) {
        bearer {
            loadTokens {
                println("---------- LOADING TOKENS!") // this is printed
            refreshTokens {
                println("---------- REFRESHING TOKENS!") // this is NOT printed
and the
is pretty simple - just adds the header if needed:
Copy code
private class UnauthorizedResponseWrapper(response: HttpResponse): HttpResponse() {
    override val call: HttpClientCall =
    override val content: ByteReadChannel = response.content
    override val coroutineContext: CoroutineContext = response.coroutineContext
    override val headers: Headers = buildHeaders {
        if (response.status == HttpStatusCode.Unauthorized && !response.headers.contains(HttpHeaders.WWWAuthenticate)) {
            println("--------- APPENDING WWWAuth header!") // this is printed!
            append(HttpHeaders.WWWAuthenticate, AuthScheme.Bearer)
    override val requestTime: GMTDate = response.requestTime
    override val responseTime: GMTDate = response.responseTime
    override val status: HttpStatusCode = response.status
    override val version: HttpProtocolVersion = response.version
As I said - I'm completely new to ktor, am I missing something here or maybe the header should be different to pass through Auth checks?

Aleksei Tirman [JB]

03/26/2022, 5:44 PM
There is an issue that prevents modifying response headers. The fix for it is available only in Ktor 2.0.0. Also, here is an issue related to your problem.