How to get started with user auth and session management
See original GitHub issueHi,
I’ve started using Javalin and found it really useful so far. However I’ve gotten stuck when adding real authentication and session handling. I’ve not used Jetty before, which I think is why I find the existing docs on that topic a bit on the short side.
I added an AccessManager
according to tutorial https://javalin.io/tutorials/auth-example, and a SessionManager
according to tutorial https://javalin.io/tutorials/jetty-session-handling-kotlin.
I also need to make sure that SessionManager does something useful to my requests. Now, I see that the Context keeps a Request object, which has a lot of methods that I suspect I should use.
So, in my login endpoint, I added this:
BasicAuthCredentials creds = ctx.basicAuthCredentials();
ctx.req.login(creds.getUsername(), creds.getPassword());`
As it is, the above gives me
[qtp1635546341-22] WARN io.javalin.core.ExceptionMapper - Uncaught exception org.eclipse.jetty.server.Authentication$Failed: Authenticated failed for username 'user1'. Already authenticated as null
What do I need to set up to make login()
work?
I also figure I should use a SessionManager to remember who is logged in. Does it also handle reading session cookies for me? The tutorial at tells me how to configure the SessionManager
, but not what it will do, or how to use it.
I notice I can probably log out a session with ctx.req.getSession().invalidate()
but what do I do to for example check whether the Context is for a logged in Session is for a certain user or Role?
HttpSession sess = ctx.req.getSession();
I looked around at the Jetty docs but they are very focused on configuring a web.xml
and not so useful for a Javalin user.
It would have been really cool to see an example project that implements Session handling!
Issue Analytics
- State:
- Created 4 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
I’m not all that familiar with how login is handled in Servlets/Jetty either, but luckily this isn’t required for auth in Javalin. Once you have a session manager configured (the default one is fine too), you can trust Jetty to keep track of the session cookie which binds the user to the server side session. Handle login however you want (basic auth, google signing, etc), then do
ctx.sessionAttribute("logged-in-user", loggedInUser)
. Iflogged-in-user
is set, then the user is logged in.I don’t really know much about
remoteUser
andisUserInRole
. Why do you need to use them? This is how I usually make my access managers:Edit:
ctx.currentUser
is justctx.attribute<String>("current-user")