我想用这个
保护我的应用程序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"""") } }
但在getOrElse
部分,我收到以下错误:
类型不匹配; found:需要对象:play.api.mvc.Result
有什么问题?
答案 0 :(得分:2)
此处action(request)
正在返回Future[Result]
,而不仅仅是Result
。因此,getOrElse
之前的整个表达式类型为Option[Future[Result]]
,它等待Future[Result]
作为getOrElse
的参数。
首先,您可以将Unauthorized.withHeaders
内容包装到Future.successfull( ... )
接下来的事情是整个表达式的结果是Future[Result]
并且它不是Action.apply(bodyParser)( ... )
的正确参数类型,但是有Action.async
方法可以处理它。
所以整个修正的块具有最小类型修正\重构
import org.apache.commons.codec.binary.Base64
def secured[A](username: String, password: String)(action: Action[A]) =
Action.async(action.parser) {
request => request.headers.get("Authorization").flatMap { authorization =>
authorization.split(" ").drop(1).headOption.filter { encoded =>
val bytes = Base64.decodeBase64(encoded.getBytes)
new String(bytes).split(":").toList match {
case u :: p :: Nil if u == username && password == p => true
case _ => false
}
}.map(_ => action(request))
}.getOrElse {
Future.successful(
Unauthorized.withHeaders(
"WWW-Authenticate" -> """Basic realm="Secured""""))
}
}
进一步注射糖可能会导致更具可读性的版本:
import org.apache.commons.codec.binary.Base64
def secured[A](username: String, password: String)(action: Action[A]) =
Action.async(action.parser) { request =>
val result = for {
authorization <- request.headers.get("Authorization")
Array(_, encoded, _*) <- Some(authorization.split(" "))
bytes = Base64.decodeBase64(encoded.getBytes)
credentials = new String(bytes).split(":").toList
List(`username`, `password`) <- Some(credentials)
} yield action(request)
result.getOrElse {
Future.successful(
Unauthorized.withHeaders(
"WWW-Authenticate" -> """Basic realm="Secured""""))
}
}
请注意,<-
左侧的解包已转换为filter
match