scala - Play : How to prevent the body parser from being invoked in case the action code does not get executed

标签 scala playframework

我创建了一个自定义Action 来防止未经授权的用户访问 protected 功能:

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 而没有执行操作代码,主体解析器仍然会被调用......并且这出乎我的意料。

也就是说,问题是:如果 SecureAction 返回 Unauthorized,我如何防止调用主体解析器(即 fsBodyParser) ?

最佳答案

看看 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/ActionBuilder 不同,它们不需要与 BodyParsers 交互。

值得一提的是@marius-soutier 的这篇精彩帖子:http://mariussoutier.com/blog/2013/09/17/playframework-2-2-action-building-action-composition/

关于scala - Play : How to prevent the body parser from being invoked in case the action code does not get executed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30396176/

相关文章:

scala - 使用 Scala 解析 XML

scala - 根据谓词拆分器将对象列表拆分为不同的列表

scala - 如何删除列表变量中的空值?

javascript - 如何将 Scala Map[String,Map[String,String]] 传递给 Js 对象

google-app-engine - Play Framework 2.3 和 GAE - Google App Engine

scala - 简洁明了的 Scala HTTP 客户端库

javascript - 对 Play REST 服务器的 Angular 2 http 请求

java - 玩! Framework JPA [RuntimeException : No EntityManager bound to this thread. Try to annotate your action method with @play.db.jpa.Transactional]

使用 JOOQ 生成器的 Playframework Evolutions

algorithm - 根据数据完成一个基于RDD的RDD