Last active
August 29, 2015 14:04
-
-
Save Rydgel/51430749e8c5a9b0de65 to your computer and use it in GitHub Desktop.
HTTP Auth Action for Scala Play 2.x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package actions | |
import play.api.Play | |
import play.api.mvc._ | |
import scala.concurrent.Future | |
import org.apache.commons.codec.binary.Base64.decodeBase64 | |
object AuthenticationAction extends ActionBuilder[Request] { | |
private val headers = "WWW-Authenticate" -> "Basic realm=\"whosmad\"" | |
private val login = Play.current.configuration.getString("auth.username").getOrElse("admin") | |
private val password = Play.current.configuration.getString("auth.password").getOrElse("admin") | |
private def getUser(request: RequestHeader): Option[List[String]] = { | |
request.headers.get("Authorization").flatMap { authorization => | |
authorization.split(" ").drop(1).headOption.flatMap { encoded => | |
new String(decodeBase64(encoded.getBytes)).split(":").toList match { | |
case c :: s :: Nil => Some(List(c, s)) | |
case _ => None | |
} | |
} | |
} | |
} | |
def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = { | |
getUser(request) match { | |
case Some(c: List[String]) if c(0) == login && c(1) == password => block(request) | |
case _ => Future.successful(Results.Unauthorized.withHeaders(headers)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment