ktorio / ktor

Framework for quickly creating connected applications in Kotlin with minimal effort
https://ktor.io
Apache License 2.0
12.85k stars 1.04k forks source link

How to set maxAge(duration) of cookie to -1 #1367

Closed kobevaliant closed 3 years ago

kobevaliant commented 5 years ago

Hi, I want the session deleted when user close browser, so I must set the cookie's maxAge to -1, but I don't know how to do it. The folowing code doesn't work

    install(Sessions) {
        cookie<FfpSession>(
            "SESSION_ID",
            directorySessionStorage(File(".sessions"), cached = true)
        ) {
            cookie.path = "/"
//            cookie.duration = Duration.ofSeconds(-1)
        }
    }

I find some code in ktor in io.ktor.sessions.SessionTransportCookie

    override fun send(call: ApplicationCall, value: String) {
        val now = GMTDate()
        val maxAge = configuration.duration?.let { it[ChronoUnit.SECONDS].coerceAtMost(Int.MAX_VALUE.toLong()) }
        val expires = maxAge?.let { now + TimeUnit.SECONDS.toMillis(maxAge) }

        val cookie = Cookie(
            name,
            transformers.transformWrite(value),
            configuration.encoding,
            maxAge?.toInt() ?: 0,
            expires,
            configuration.domain,
            configuration.path,
            configuration.secure,
            configuration.httpOnly,
            configuration.extensions
        )

        call.response.cookies.append(cookie)
    }

It seems that expires is set without considerring maxAge of -1?

cy6erGn0m commented 5 years ago

One usually can't deal with negative time periods so nobody knows what is a duration of -1 seconds.

cy6erGn0m commented 5 years ago

According to MDN https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies#Session_cookies

The cookie created above is a session cookie: it is deleted when the client shuts down, because it didn't specify an Expires or Max-Age directive.

So what you need is missing both Expires and MaxAge that you can achieve by setting duration to null.

e5l commented 3 years ago

Released in 1.3.0