Hello! Nice to meet everyone! Random question reg...
# ktor
f
Hello! Nice to meet everyone! Random question regarding the Sessions plugin. Is it possible to use this plugin to just simply store a JWT string in the cookie. I want to opt to not use Authorization headers for my use case. So something like
Copy code
cookie<String>("SESSION") { ... }
The documentation just alludes to always signing/transforming the cookie (as well as making a data class instead of using String), but my JWT is already encrypted. Then I'm calling
Copy code
val accessToken = "eyJhbG..."
call.sessions.set(accessToken)
But the header response looks like
Copy code
Set-Cookie: SESSION=length%3D%2523i536; ...
instead of what I wanted to expect as
Copy code
Set-Cookie: SESSION=eyJhbG.....
Thanks! And if there's no easy solution, no big deal. I can just manually set the cookie header myself, just was curious if I could use the plugin just because its cleaner.
a
You can use the
KotlinxSessionSerializer
with the JSON format to serialize a String into the cookie value.
Copy code
install(Sessions) {
    cookie<String>("user_session") {
        serializer = KotlinxSessionSerializer(Json)
        // ...
    }
}
❤️ 1
f
Excellent, I will give this a shot!
@Aleksei Tirman [JB] Finally got around to testing this out. One small, but non-blocking issue for me, is that I saw is that by default the cookie encoding adds
%22 ... %22
to before and after the JWT string.
Copy code
cookie.encoding = CookieEncoding.URI_ENCODING (Default)
  SESSION=%22 ...... %22

cookie.encoding = CookieEncoding.RAW =
  java.lang.IllegalArgumentException: The cookie value contains characters that cannot be encoded in RAW format.  Consider URL_ENCODING mode

cookie.encoding = CookieEncoding.DQUOTES =
  java.lang.IllegalArgumentException: The cookie value contains characters that cannot be encoded in DQUOTES format. Consider URL_ENCODING mode

cookie.encoding = CookieEncoding.BASE64_ENCODING
  // Works with no exceptions -- but BASE64 encoding an already signed JWT is inefficient, and the final string is even longer than the original
However, I think I can work with the
%22
around my JWT for now. This allows me to use the sessions library instead of doing everything manually, thank you!