播放[2.5.x]自定义正文解析器以获取原始正文并将其与请求

时间:2016-04-14 20:14:29

标签: scala playframework playframework-2.5

我有一个帖子请求带有一个hmac标头,我需要匹配正文。此标头是使用请求的原始主体创建的,我无法更改它。请求的内容类型是application / json。目前似乎无法访问请求的原始主体以及请求的json编码主体,因此我尝试创建自定义主体解析器和操作以将原始主体和原始请求捆绑在一起并通过他们。

我正在尝试复制这些人实现https://victorops.com/blog/capturing-raw-requests-play/,但它是预先播放2.5所以使用iteratees而不是akka stream。

这是我到目前为止所做的:

BodyParser和Case Classes

object RequestArchiver {
  case class RawRequest[A](request: Request[A], raw: ByteString) extends WrappedRequest[A](request)
  case class WrappedPayload[A](wrapped: A, raw: ByteString)

  def wrappedBodyParser[B](wrapped: BodyParser[B])  (implicit exCtx: ExecutionContext): BodyParser[WrappedPayload[B]] =
    BodyParser("raw-memo") { (request: RequestHeader) =>
    val raw: Accumulator[ByteString, Either[Result, RawBuffer]] = BodyParsers.parse.raw(request)
      val ret = raw.map {
      case Left(result) =>
        Left(result)
      case Right(buffer: RawBuffer) =>
        val bytes = buffer.asBytes().getOrElse(ByteString.empty)
        Right(WrappedPayload(wrapped(request), bytes))
    }
    ret
  }
}

这不会编译错误

Error:(33, 5) type mismatch;
 found   : play.api.libs.streams.Accumulator[akka.util.ByteString,Product with Serializable with scala.util.Either[play.api.mvc.Result,controllers.RequestArchiver.WrappedPayload[play.api.libs.streams.Accumulator[akka.util.ByteString,Either[play.api.mvc.Result,B]]]]]
 required: play.api.libs.streams.Accumulator[akka.util.ByteString,Either[play.api.mvc.Result,controllers.RequestArchiver.WrappedPayload[B]]]
    ret
    ^

现在我可以看到那个试图告诉我的内容,我明白我只是不知道如何修复它。我想解决方案是在链接的第15行和第24行victorops示例之间,但我不知道如何将这些行转换为2.5版本

重要的自定义操作

def extractRaw[A](parser: BodyParser[A])(block: (RawRequest[A]) => Future[Result])(implicit ctx: ExecutionContext) =
    Action.async(RequestArchiver.wrappedBodyParser(parser)) { implicit request =>
      val rawRequest = RawRequest(Request(request, request.body.wrapped), request.body.raw)
      block(rawRequest)
    }

1 个答案:

答案 0 :(得分:0)

我是Play的新手,但如何使用更简单的raw正文解析器呢。我做了一个快速测试。

class Tester extends Controller {
  def handleRaw = Action(parse.raw) { implicit request =>
    request.body.asBytes().map(b => Ok(s"Request body has ${b.size} bytes")).getOrElse(NoContent)
  }
}

curl -v --data "a=b&c=d" http://localhost:9000/test/raw

*   Trying ::1...
* Connected to localhost (::1) port 9000 (#0)
> POST /test/raw HTTP/1.1
> Host: localhost:9000
> User-Agent: curl/7.43.0
> Accept: */*
> Content-Length: 7
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 7 out of 7 bytes
< HTTP/1.1 200 OK
< Content-Length: 85
< Content-Type: text/plain; charset=utf-8
< Date: Mon, 15 Aug 2016 09:41:30 GMT
< 
Request body has 7 bytes
* Connection #0 to host localhost left intact