簡単な例を見つけて、以下のコードが機能するようにしました。
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") {}
}