-
-
Save takumakei/4248507 to your computer and use it in GitHub Desktop.
HTTP Basic Authorization for Play 2.0
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 org.apache.commons.codec.binary.Base64.decodeBase64 | |
import play.api._ | |
import play.api.mvc._ | |
trait BasicRealm { | |
def name: String | |
def authorize(user: String, password: String): Boolean | |
} | |
object BasicRealm extends Controller { | |
def apply[A](realm: BasicRealm)(action: Action[A]) = Action(action.parser) { request => | |
request.headers.get("Authorization").flatMap { authorization => | |
authorization.split(" ").drop(1).headOption.filter { encoded => | |
new String(decodeBase64(encoded.getBytes)).split(":") match { | |
case Array(u, p) if realm.authorize(u, p) => true | |
case _ => false | |
} | |
}.map(_ => action(request)) | |
}.getOrElse { | |
val k = "WWW-Authenticate" | |
val v = "Basic realm=\""+realm.name+"\"" | |
Unauthorized.withHeaders(k -> v) | |
} | |
} | |
} |
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
val realm = new BasicRealm { | |
val name = "Secret" | |
def authorize(user: String, password: String) = { | |
user == "admin" && password == "1234secret" | |
} | |
} | |
def myAction = BasicRealm(realm) { | |
Action { request => | |
Ok | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment