Bubble Foundry

Authenticating Requests in Lift Using HTTP Dispatch Guards

by Peter.

The canonical – I’m making a leap to say that, but why not – way to add REST APIs to a Lift app is to append them to one of the app’s dispatch tables, either stateful or stateless. David and Tim have examples of using them to ensure a user is logged in, however both their examples do so by checking an existing SessionVar.

Here’s how to do so using only information in the request, specifically checking HTTP Basic authentication information against a database:

 * In the companion object of my Mapper model
// code to authenticate stateless API requests (see Boot.scala)
def reqPasses(req: Req): Boolean = {
  // hack to get access to the class' credentials method
  val auth = HttpBasicAuthentication("StatelessAPI") {
    case (key, secret, _) => true
  auth.credentials(req) match {
    case Full((k, s)) => count(By(key, k), By(secret, s)) > 0
    case _ => false
val httpBasic: PartialFunction[Req, Unit] = {
  case req if reqPasses(req) => 
 * In Boot.scala
// stateless api -- no session created
LiftRules.statelessDispatchTable.append(Client.httpBasic guard StatelessAPI)

The key thing to realize is that the PartialFunction used to guard the API takes, as you’d hope, a Req. It took me a while to figure this out, as both Tim’s and David’s examples don’t use the value passed to the PartialFunction. Of course now I see that it’s right there in the PartialFunction’s type signature, so there you go for my great Scala knowledge!