Thomas Hormes
07/14/2025, 6:10 PMauthenticate("session-auth", optional=true) { ... }
and then retrieve the principal, or should i check whether the corresponding session is set, get the session (cookie) data and then check if the session is valid in each route?Thomas Hormes
07/14/2025, 6:13 PMAleksei Tirman [JB]
07/15/2025, 11:50 AMThomas Hormes
07/15/2025, 6:31 PMAleksei Tirman [JB]
07/16/2025, 10:04 AMfun ApplicationCall.baseTemplateModel(): Map<String, Any?> {
val user = sessions.get<UserSession>()
return mapOf("user" to user)
}
Here is a usage example:
routing {
get("/login/{name}") {
val name = call.parameters["name"] ?: return@get call.respond(HttpStatusCode.BadRequest)
call.sessions.set(UserSession(name))
}
get("/a") {
call.respond(ThymeleafContent("index", call.baseTemplateModel() + mapOf("body" to 123)))
}
get("/b") {
call.respond(ThymeleafContent("index", call.baseTemplateModel() + mapOf("body" to 456)))
}
}
When the web context is supported, the session object should be automatically stored in the session attributes.Thomas Hormes
07/16/2025, 11:16 AMcall.sessions.get
? 🙂Aleksei Tirman [JB]
07/16/2025, 11:18 AMThomas Hormes
07/16/2025, 11:25 AMsession<UserSessionData>("auth-session") {
validate { session ->
// Check if session is valid by looking the session up in the DB
}
challenge {
call.respondRedirect("/login")
}
}
I am doing the validation of the session via the plugin.
Now I see only three options:
• I wrap every route with authenticate("auth-session", optional = true) { ...
thus making my code pretty deeply nested
• Or I do something like you did getting the session with an extension function on ApplicationCall and doing the validation of the session here again.
• I could also wrap all my routes in a single authenticate block, and then have all routes where the authentication is optional in a separate function calling the `routing`block.
However i feel Option two and three are kind of smelly, because for option two i feel like all authentication logic belongs in the Authentication Plugin installation setup and accessing the session immediately via call.sessions
feels like I'd go around that by not using call.principal
.
For Option three it feels kind of smelly because I'd pull the authentication further away from the routes (which to my mind is where it belongs)
And for Option One I feel it'd clutter code unnecesarily.
I was hoping for you to help me either see a fourth option, that I simply dont know yet. Ease my concerns on one of the Options. Or to tell me that this is basically what amounts to a "me-issue" 😅Thomas Hormes
07/16/2025, 11:37 AMAleksei Tirman [JB]
07/16/2025, 1:19 PM/login
would require authentication. Its handler would then set the user's session on successful authentication. All other endpoints would utilize the solution described above.