【问题标题】:How to get the raw request body in Play?如何在 Play 中获取原始请求正文?
【发布时间】:2019-12-14 17:38:55
【问题描述】:

我的 play 应用程序有一个用于从 Stripe 接收 webhook 的端点。

为了验证 webhook,需要将请求正文与签名和签名密钥进行比较。这要求我可以访问发送的原始请求正文。

但是,Play 似乎更改了请求正文,我无法访问原始内容。这会导致计算的签名发生变化,验证失败。更多信息:https://stackoverflow.com/a/43894244/49153

这是我的代码:

@Singleton
class WebhookController @Inject()(cc : ControllerComponents,
                                  env: Env)
                                 (implicit ec: ExecutionContext)
  extends AbstractController(cc) {

  private val log = Logger("WebhookController")


  def index(): Action[AnyContent] = Action.async { implicit req =>

      val signature =
          req.headers.headers.find(_._1 == "Stripe-Signature").map(_._2).getOrElse("").trim

      if (verifySignature(req.body.toString, signature, env.webhookSecretKey))
        Future.successful(ok("ok"))
      else
          Future.successful(ok("Couldn't verify signature"))
  }


}

这里我尝试使用 req.body.toString 访问正文,但它看起来是反序列化的 json 而不是原始正文。

使用req.body.asRaw 返回无。

有什么想法吗?

【问题讨论】:

    标签: scala playframework


    【解决方案1】:

    通过使用Action.async(parse.raw) 解决了这个问题,然后使用req.body.asBytes().map(_.utf8String).getOrElse("") 获取正文的原始字符串。更多信息:https://www.playframework.com/documentation/2.7.x/ScalaBodyParsers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      • 2016-04-24
      • 2016-01-27
      • 2019-01-07
      • 2013-09-13
      相关资源
      最近更新 更多