Last active
March 27, 2019 11:30
-
-
Save owainlewis/50c264793a8cad2909ec to your computer and use it in GitHub Desktop.
Play Framework Basic Auth Action (play, scala, basic auth)
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
class ControllerWithBasicAuth extends Controller { | |
private val WithBasicAuth = new BasicAuthAction("user", "pass") | |
def index = WithBasicAuth { | |
Ok("Correct basic auth credentials") | |
} | |
} |
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
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
License?