Ruby on rails Heroku和Rails 3.1中特定于SSL的主机名
我目前有一个设置,在我的应用程序控制器中,我强制SSL或http在我需要它的地方使用这个before\u过滤器:Ruby on rails Heroku和Rails 3.1中特定于SSL的主机名,ruby-on-rails,ruby,ssl,https,hostname,Ruby On Rails,Ruby,Ssl,Https,Hostname,我目前有一个设置,在我的应用程序控制器中,我强制SSL或http在我需要它的地方使用这个before\u过滤器: def force_ssl if params[:controller] == "sessions" if !request.ssl? && Rails.env.production? redirect_to :protocol => 'https://', :status => :moved_permanently end
def force_ssl
if params[:controller] == "sessions"
if !request.ssl? && Rails.env.production?
redirect_to :protocol => 'https://', :status => :moved_permanently
end
else
if request.ssl? && Rails.env.production?
redirect_to :protocol => 'http://', :status => :moved_permanently
end
end
end
我想做的是使用
https://secure.example.com
使用SSL时,请继续使用http://example.com
不使用SSL时。是否有一种方法可以根据我是否使用SSL在主机名之间切换?首先,我将演示如何在当前和早期版本的Rails中强制使用SSL,然后在最后我发布了如何并行使用HTTP和HTTPS,这正是我认为您需要的
Rails>=3.1只需在您的环境配置中使用
config.force\u ssl=true
。# config/application.rb
module MyApp
class Application < Rails::Application
config.force_ssl = true
end
end
# config/application.rb
module MyApp
class Application < Rails::Application
config.force_ssl = false
end
end
# config/environments/production.rb
MyApp::Application.configure do
config.force_ssl = true
end
并行启用HTTPS和HTTP
Rack::SSL
有一个非常有趣且未记录的特性。您可以传递一个:exclude
选项,以确定何时启用/禁用HTTPS
以下代码仅在请求来自HTTPS连接时才启用Rack::SSL
及其所有筛选器
config.middleware.insert_before ActionDispatch::Static, Rack::SSL, :exclude => proc { |env| env['HTTPS'] != 'on' }
以下两个URL都将继续工作,但第一个URL将触发Rack::SSL
过滤器
https://secure.example.com
http://example.com
当身份验证完成后,任何人都可以使用firesheep等免费会话黑客firefox插件对其会话进行黑客攻击时,为什么还要强迫用户通过SSL进行身份验证呢。如果您试图以这种方式使用SSL,您就不能保护您的用户。相反,如果站点的某些部分需要通过SSL交付,那么从实际的安全角度来看,站点的每个部分也可能需要通过SSL交付(或者,至少,验证后的每个部分)但当我不需要SSL时,我没有找到一种方法让它强制使用http,所以我只是在我的应用程序控制器中推出了自己的解决方案。有没有一种自定义force_ssl的方法?您可以在ForceSSL模块中编写一个自定义类方法,它的作用与ForceSSL正好相反,如果您愿意,我可以发布一个示例?
config.middleware.insert_before ActionDispatch::Static, Rack::SSL, :exclude => proc { |env| env['HTTPS'] != 'on' }