Skip to content

Instantly share code, notes, and snippets.

@owainlewis
Last active March 27, 2019 11:30
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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)
}
}
@dportabella
Copy link

From: https://stackoverflow.com/questions/43835032/play-2-6-actionbuilder

In Play2.6, "The Scala ActionBuilder trait has been modified to specify the type of the body as a type parameter, and add an abstract parser member as the default body parsers. You will need to modify your ActionBuilders and pass the body parser directly."

Play 2.6 injects a ControllerComponents, which has a default body parser. Maybe this helps:

  override protected def executionContext: ExecutionContext = cc.executionContext
  override def parser: BodyParser[AnyContent] = cc.parsers.defaultBodyParser

And add this to BasicAuthAction class @Inject()(val cc: ControllerComponents).

@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