Skip to content

Instantly share code, notes, and snippets.

@takumakei
Forked from guillaumebort/Secured.scala
Created December 10, 2012 05:05
Show Gist options
  • Save takumakei/4248507 to your computer and use it in GitHub Desktop.
Save takumakei/4248507 to your computer and use it in GitHub Desktop.
HTTP Basic Authorization for Play 2.0
import org.apache.commons.codec.binary.Base64.decodeBase64
import play.api._
import play.api.mvc._
trait BasicRealm {
def name: String
def authorize(user: String, password: String): Boolean
}
object BasicRealm extends Controller {
def apply[A](realm: BasicRealm)(action: Action[A]) = Action(action.parser) { request =>
request.headers.get("Authorization").flatMap { authorization =>
authorization.split(" ").drop(1).headOption.filter { encoded =>
new String(decodeBase64(encoded.getBytes)).split(":") match {
case Array(u, p) if realm.authorize(u, p) => true
case _ => false
}
}.map(_ => action(request))
}.getOrElse {
val k = "WWW-Authenticate"
val v = "Basic realm=\""+realm.name+"\""
Unauthorized.withHeaders(k -> v)
}
}
}
val realm = new BasicRealm {
val name = "Secret"
def authorize(user: String, password: String) = {
user == "admin" && password == "1234secret"
}
}
def myAction = BasicRealm(realm) {
Action { request =>
Ok
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment