如何在Play中获取原始请求正文? [英] How to get the raw request body in Play?

查看:98
本文介绍了如何在Play中获取原始请求正文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的播放应用程序具有一个端点,用于接收来自Stripe的Web钩子.

My play application has an endpoint for receiving webhooks from Stripe.

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

In order to verify the webhooks, the request body needs to be compared against a signature and a signing key. This requires that I have access to the raw request body, as sent.

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

However, it seems that Play alters the request body, and I can't get access to the raw contents. This causes the computed signature to change, and the verification fails. More info: 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而不是原始主体.

Here I'm trying to access the body using req.body.toString but it looks to be the deserialized json rather than the raw body.

使用req.body.asRaw返回无.

有什么想法吗?

推荐答案

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

Solved this by using Action.async(parse.raw) and then doing req.body.asBytes().map(_.utf8String).getOrElse("") to obtain the raw string of the body. Some more info: https://www.playframework.com/documentation/2.7.x/ScalaBodyParsers

这篇关于如何在Play中获取原始请求正文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆