auramo
auramo

Reputation: 13357

Scalatra Basic Authentication for part of an application

I'm trying to figure out how to write an app which has basic authentication enabled for certain URLs. The authenticated part should not have form-based authentication, just the default login I can do easily from Javascript/JQuery. I've seen a few examples which look complicated and when I try to use them, lot of the stuff is deprecated and in general it seems to be a lot of work to get the example code even to compile now.

So are those examples still the best Scalatra has to offer or is there a simpler way now?

I'm using Scalatra (with scalatra-auth) version 2.1.1.

Upvotes: 1

Views: 1105

Answers (2)

futurechimp
futurechimp

Reputation: 554

There's now a Scalatra guide on authentication which covers the basic auth case you're looking for. See http://scalatra.org/2.2/guides/http/authentication.html

Scalatra's auth integrations should not have changed between Scalatra 2.1.1 (which you're using) and the soon-to-be-released Scalatra 2.2.0, so the guide should still be valid for you.

Upvotes: 1

auramo
auramo

Reputation: 13357

Found an easier example and got the below code working.

package mc.nulty

import org.scalatra.auth.strategy.BasicAuthStrategy.BasicAuthRequest
import org.scalatra._
import scalate.ScalateSupport

class McNultyServlet extends ScalatraServlet with ScalateSupport {

  get("/") {
    basicAuth
    <html>
      <body>
        <h1>Hello, world!</h1>
        Say <a href="hello-scalate">hello to Scalate</a>.
      </body>
    </html>
  }

  notFound {
    // remove content type in case it was set through an action
    contentType = null
    // Try to render a ScalateTemplate if no route matched
    findTemplate(requestPath) map { path =>
      contentType = "text/html"
      layoutTemplate(path)
    } orElse serveStaticResource() getOrElse resourceNotFound()
  }

  protected def basicAuth() = {
    val req = new BasicAuthRequest(request)

    def notAuthenticated() {
      response.setHeader("WWW-Authenticate", "Basic realm=\"%s\"" format "mc-nulty")
      halt(401, "Unauthenticated")
    }

    if(!req.providesAuth) {
      notAuthenticated
    }
    if(!req.isBasicAuth) {
      halt(400, "Bad Request")
    }
    val user = DAO.validateLoginPassword(req.username, req.password)
    if (user != null)
      response.setHeader("REMOTE_USER", "user.id")
    else {
      notAuthenticated
    }
    Option(user)
  }

  object DAO {
    def validateLoginPassword(username: String, password: String) : User = {
      if (username.equals("foo")) new User()
      else null
    }
  }
  class User(val id:String = "dummyid") {}
}

Upvotes: 3

Related Questions