Skip to content

Instantly share code, notes, and snippets.

@owainlewis
Last active March 27, 2019 11:30
Show Gist options
  • Save owainlewis/50c264793a8cad2909ec to your computer and use it in GitHub Desktop.
Save owainlewis/50c264793a8cad2909ec to your computer and use it in GitHub Desktop.
Play Framework Basic Auth Action (play, scala, basic auth)
class ControllerWithBasicAuth extends Controller {
private val WithBasicAuth = new BasicAuthAction("user", "pass")
def index = WithBasicAuth {
Ok("Correct basic auth credentials")
}
}
import play.api.mvc._
import scala.concurrent.Future
class BasicAuthAction(username: String, password: String) extends ActionBuilder[Request] with ActionFilter[Request] {
private val unauthorized =
Results.Unauthorized.withHeaders("WWW-Authenticate" -> "Basic realm=Unauthorized")
def filter[A](request: Request[A]): Future[Option[Result]] = {
val result = request.headers.get("Authorization") map { authHeader =>
val (user, pass) = decodeBasicAuth(authHeader)
if (user == username && pass == password) None else Some(unauthorized)
} getOrElse Some(unauthorized)
Future.successful(result)
}
private [this] def decodeBasicAuth(authHeader: String): (String, String) = {
val baStr = authHeader.replaceFirst("Basic ", "")
val decoded = new sun.misc.BASE64Decoder().decodeBuffer(baStr)
val Array(user, password) = new String(decoded).split(":")
(user, password)
}
}
@hrieke
Copy link

hrieke commented Jan 17, 2019

License?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment