Thursday, March 22, 2012

Simplest Authentication in Lift

Lift has been an interesting experience so far, particularly since I'm learning Scala at the same time. Lift comes with quite a few built-in mechanisms to handle various features, such as authentication, authorization and role-based access control.

A lot of the documentation utilizes these built-ins to good effect, but because the core mechanisms are complete skipped, you have no idea where to start if you have to roll your own authentication. A suggestion for Lift documentation: cover the basic introduction first, then show how Lift builds on that foundation.

I present here the simplest possible authentication scheme for Lift, inspired by this page on the liftweb wiki:

object isLoggedIn extends SessionVar[Boolean](false)
...

// in Boot.scala
LiftRules.loggedInTest = Full(() => isLoggedIn.get)

That last line only needs to return a boolean. If you wish to include this with Lift's white-listed menu system, you merely need to add this sort of test:

val auth = If(() => !Authentication.user.isEmpty,
              () => RedirectResponse("/index"))
val entries = 
    Menu(Loc("Login", "index" :: Nil, "Login", Hidden)) :: 
    Menu(Loc("Some Page", "some-page" :: Nil, "Some-Page", auth)) ::
    Nil
SiteMap(entries:_*)

Any request other than /index that is not authenticated, ie. isLoggedIn.get returns false, will redirect to /index for login.

One caveat: since the authenticated flag session-level data, you are vulnerable to CSRF attacks unless you utilize Lift's built-in CSRF protection, where input names are assigned GUIDs. This is the default, but since it is easy to circumvent this to support simple query forms and the like, it's worth mentioning.

No comments: