开发者

Rack and rack.request.form_vars / rack.request.form_hash

开发者 https://www.devze.com 2023-02-11 05:33 出处:网络
I am doing some middleware that changes the authenticity_token param before it gets to Rails. I can see that env开发者_Go百科.inspect gives both rack.request.form_vars and rack.request.form_hash. Bo

I am doing some middleware that changes the authenticity_token param before it gets to Rails.

I can see that env开发者_Go百科.inspect gives both rack.request.form_vars and rack.request.form_hash. Both contains the authenticity token. Which one does Rails use and why does Rack provide both?


Let's look at the source! The both variables come from using the Rack::Request helper class. It provides a nice interface to the request parameters. It's not necessary for Rack applications to use it, but Rails does use it.

The variables are for Rack::Request's internal use. rack.request.form_vars contains the unparsed POST body and rack.request.form_hash contains the parsed hash. ActionDispatch::Request inherits from Rack::Request and it gets the parameters using Rack::Request#POST, which reads the latter variable. You could use Rack::Request yourself to modify it.

class YourMiddleware
  def initialize(app)
    @app = app
  end 

  def call(env)
    req = Rack::Request.new(env)
    req.POST["authenticity_token"] = "foo"
  end
end


If you have a recent copy of rack that includes this pull request, you can use Rack::Request#update_param:

request = Rack::Request.new(env)
request.update_param :auth_token, 'XXXXXXXXXXXXXXXX'

Just like the req.POST solution above, this will persist in the env that is passed among middlewares - but it's a higher-level call meant to deal with situations like yours.

0

精彩评论

暂无评论...
验证码 换一张
取 消