Hey guys, I'm new to ktor and having problems with...
# ktor
k
Hey guys, I'm new to ktor and having problems with Auth plugin on mobile. Our backend returns 401 (Unauthorized) without the
WWW-Authenticate
header set, as a result the
refreshToken
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(Logging)
    install("Fix Unauthorized headers") {
        receivePipeline.intercept(HttpReceivePipeline.Before) { response ->
            println("----------- INTERCEPTING!") // this is printed
            proceedWith(UnauthorizedResponseWrapper(response))
        }
    }
    install(Auth) {
        bearer {
            loadTokens {
                println("---------- LOADING TOKENS!") // this is printed
                ...
            }
            refreshTokens {
                println("---------- REFRESHING TOKENS!") // this is NOT printed
                ...
            }
        }
    }
and the
UnauthorizedResponseWrapper
is pretty simple - just adds the header if needed:
Copy code
private class UnauthorizedResponseWrapper(response: HttpResponse): HttpResponse() {
    override val call: HttpClientCall = response.call
    override val content: ByteReadChannel = response.content
    override val coroutineContext: CoroutineContext = response.coroutineContext
    override val headers: Headers = buildHeaders {
        appendAll(response.headers)
        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?
a
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.