gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:53:35 25 4
gpt4 key购买 nike

我创建了一个自定义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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com