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

Dirk

04/08/2022, 12:47 PM
Hi all, I have a problem reading a cookie with the Ktor JS client. On the server side (also Ktor 2.0Beta1) a session is created, which should be stored in a cookie on the client side. My problem now is that I can't access the session cookie from the Ktor client. In the following code, the cookie is not accessible in the header or with the specialized function, although I can see in the browser's developer console that the server sends the cookie along in the header. The web page with the client comes from localhost:8080 and the query with the cookie is about the server localhost:9012 - that shouldn't be a problem or should it. Where is my error?
Copy code
val clientTopic = HttpClient {
    install(Logging)
    install(ContentNegotiation) {
        json()
    }
    install(HttpCookies) {
        storage = AcceptAllCookiesStorage() // default
    }

    defaultRequest {
        ...
    }
}
....
        val response = clientTopic.get(href(ResourcesFormat(), ApiTopicMS.Topic.V1.Laden(onlineLinkID = onlineLinkID)))

        when (response.status) {
            HttpStatusCode.OK -> {
                <http://console.info|console.info>("Cookies from server: ${response.setCookie()}")
                val setCookieHeader = response.headers["Set-Cookie"]
                <http://console.info|console.info>("Cookie from header: $setCookieHeader")
                <http://console.info|console.info>(response.headers.names())
                response.headers.forEach { s, strings ->
                    <http://console.info|console.info>("s: $strings")
                }
                response.body<TopicDTO>()
            }
            else -> {
                console.error("Topic konnte nicht geladen werden. Status: ${response.status}")
                null
            }
        }
a

Aleksei Tirman [JB]

04/08/2022, 2:36 PM
If your code is executed in a browser environment then there is no way to access the
Set-Cookie
header. You can find more information here.
d

Dirk

04/13/2022, 12:01 PM
Thanks for the hint, I was not aware of that. But now I have the challenge to get a session and send it to Ktor via a normal download link... 🤔
5 Views