我已创建了一个自定义Action
,可防止未经授权的用户访问受保护的功能:
class SecureAction extends ActionBuilder[SecureRequest] {
def invokeBlock[A](request: Request[A], block: SecureRequest[A] => Future[Result]) = {
...
future.flatMap {
case token if (!isAuthorized(token)) =>
Logger.info(s"request ${request.path} not authorized: user ${token.username} does not have required privileges")
Future.successful(Unauthorized(error(requestNotAuthorized))))
case ...
}
}
}
如果当前用户未获得授权,则SecureAction
将返回Unauthorized
,并且永远不会执行提供的操作代码。以下是我Controller
的样子:
object MyController extends Controller {
...
def saveFile = SecureAction.async(fsBodyParser) { implicit request =>
// code here not executed if current user has not required privileges
...
}
}
问题是即使当前用户未经授权而且SecureAction
在没有执行操作代码的情况下返回Unauthorized
,仍然会调用正文解析器......这不是我所期待的
那就是说,问题是:如果fsBodyParser
返回SecureAction
,我该如何阻止身体解析器(即Unauthorized
)被调用?
答案 0 :(得分:2)
看看EssentialAction(https://www.playframework.com/documentation/2.2.x/api/scala/index.html#play.api.mvc.EssentialAction)
如您所见,这是EssentialAction的定义:
trait EssentialAction extends (RequestHeader) ⇒ Iteratee[Array[Byte], SimpleResult] with Handler
因此,如果您想在请求标头级别操作,请选择EssentialActions。与Action / ActionBuilders不同,他们不需要与BodyParsers进行互动。
值得一提的是@ marius-soutier的这篇精彩帖子:http://mariussoutier.com/blog/2013/09/17/playframework-2-2-action-building-action-composition/