【问题标题】:How to prevent force_ssl from destroying params in redirect?如何防止 force_ssl 在重定向中破坏参数?
【发布时间】:2011-12-06 08:18:32
【问题描述】:

我有以下路线:

resources :widgets do
  resources :orders
end

这样一个请求,例如to /widgets/1/orders/new 转到 OrderController,它可以访问 params[:widget_id] 以了解正在购买的小部件。

问题是这样的:我在 OrderController 中使用了force_ssl。这导致请求:

http://www.example.com/widgets/1/orders/new

被重定向 (302) 到:

https://www.example.com/

换句话说,force_ssl 正在完成它的工作(重定向到 URL 的 https 协议版本),但正在破坏过程中路由的动态段指定的参数。我怎样才能防止这种情况发生(最好)或以最不冒犯的方式解决它?

请注意,这是托管在 Heroku 上的,例如Apache 重定向对我不起作用。

【问题讨论】:

    标签: ruby-on-rails routes ruby-on-rails-3.1 actioncontroller


    【解决方案1】:

    我相信 force_ssl 的默认行为是将参数从非安全连接传递到安全连接。如果这不是您想要的行为,您可以尝试通过添加这样的初始化程序来覆盖 force_ssl 函数:

    #
    # Pass parameters in SSL redirects
    #
    module ActionController
      module ForceSSL
        module ClassMethods
          def force_ssl(options = {})
            host = options.delete(:host)
            before_filter(options) do
              if !request.ssl? && !Rails.env.development?
    
                secure_params = request.params.clone
                [:only, :except, :protocol, :status, :host].each {|s| secure_params.delete(s)}
    
                redirect_options = {:protocol => 'https://', :status => :moved_permanently}
                redirect_options.merge!(:host => host) if host
                redirect_to redirect_options.merge(secure_params)
              end
            end
    
          end
        end
      end
    end
    

    【讨论】:

    • 感谢您的回答。不幸的是,我已经在整个应用程序(即 config/environments/production.rb 中的config.force_ssl = true)中部署了该应用程序,作为一个不太理想的解决方法。由于我无法在我的生产服务器上进行测试,因此我无法判断您的解决方案是否有效。 :-\
    • 为我工作,谢谢!您是否为此创建了拉取请求?
    • 谢谢!你真的救了我!
    • 我没有提交拉取请求。我没有对这个补丁进行很多测试,可能存在错误。此解决方案的一个可能问题是当您收到 POST 并且重定向作为带有参数的 GET 进行时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 2012-03-05
    • 2011-05-20
    • 2016-02-06
    相关资源
    最近更新 更多