Created
April 7, 2012 12:05
-
-
Save guillaumebort/2328236 to your computer and use it in GitHub Desktop.
HTTP Basic Authorization for Play 2.0
This file contains 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
def Secured[A](username: String, password: String)(action: Action[A]) = Action(action.parser) { request => | |
request.headers.get("Authorization").flatMap { authorization => | |
authorization.split(" ").drop(1).headOption.filter { encoded => | |
new String(org.apache.commons.codec.binary.Base64.decodeBase64(encoded.getBytes)).split(":").toList match { | |
case u :: p :: Nil if u == username && password == p => true | |
case _ => false | |
} | |
}.map(_ => action(request)) | |
}.getOrElse { | |
Unauthorized.withHeaders("WWW-Authenticate" -> """Basic realm="Secured"""") | |
} | |
} |
This file contains 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
def myAction = Secured("admin", "1234secret") { | |
Action { request => | |
Ok | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think that line 4 of Secured.scala needs to be updated to handle
:
in password. As noted in this blog post the password can have a colon which means that code above wouldn't handle those passwords properly.Just a note, that blog post actually doesn't handle colons correctly, I have made a note on the author's gist and forked my own which handles colons correctly here