HMAC,Elixir,Plug.Conn(尝试调用多次read_body)

4
我遇到了一个问题,即某些东西在Plug.Parsers.JSON获取请求管道之前读取了http请求的正文。由于这个原因,json插件中的read_body超时——你不能读两次正文。
我们的管道中有一个较早的插件实现了HMAC,并且在某些情况下读取正文。在Plug中,正文使用的模式是什么?我的意思是,如果我们只能读一次,并且必须在Plug.Parsers.JSON中解码,那么...它不会起作用。
后续问题。在生成HMAC哈希时,我们需要包含请求正文吗?我的意思是,对我来说,感觉必须这样做,但我已经陷入了死循环。
谢谢!
1个回答

3
您可以向Plug.Parsers传递自定义的:body_reader选项,以便缓存请求正文以供后续使用。
在解析器之前不要读取请求正文,而是缓存请求正文,以便稍后从想要哈希它的插件中读取。

选项

:body_reader - 可选替换(或包装)Plug.Conn.read_body/2的函数,提供一个访问在正文被解析和丢弃之前的原始正文的函数。它的标准格式为{Module, :function, [args]} (MFA),默认为{Plug.Conn, :read_body, []}

示例

Sometimes you may want to customize how a parser reads the body from the connection. For example, you may want to cache the body to perform verification later, such as HTTP Signature Verification. This can be achieved with a custom body reader that would read the body and store it in the connection, such as:

defmodule CacheBodyReader do
  def read_body(conn, opts) do
    {:ok, body, conn} = Plug.Conn.read_body(conn, opts)
    conn = update_in(conn.assigns[:raw_body], &[body | (&1 || [])])
    {:ok, body, conn}
  end
end

which could then be set as:

plug Plug.Parsers,
  parsers: [:urlencoded, :json],
  pass: ["text/*"],
  body_reader: {CacheBodyReader, :read_body, []},
  json_decoder: Jason

它是在插件v1.5.1中添加的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接