Use SSL with ssl_requirement in a Rails 2 application

I have a Rails application that needs to be run under SSL. I tried ssl_requirement, but it seems to me that I should enter all the actions in each controller.

Is there any method that I can add before filter in the application controller using ssl_requirement so that applications are automatically redirected to https when the user request is in http?

Thanks to everyone. :)

+20
ruby-on-rails ssl ruby-on-rails-2
Oct 05 '10 at 7:51
source share
3 answers

Use middleware for the rack .

# lib/force_ssl.rb class ForceSSL def initialize(app) @app = app end def call(env) if env['HTTPS'] == 'on' || env['HTTP_X_FORWARDED_PROTO'] == 'https' @app.call(env) else req = Rack::Request.new(env) [301, { "Location" => req.url.gsub(/^http:/, "https:") }, []] end end end # config/environment.rb config.middleware.use "ForceSSL" 
+32
Oct 05 '10 at
source share

You can try to run a test if the request is in ssl or not in the before_filter file in your application.

 class Application < AC::Base before_filter :need_ssl def need_ssl redirect_to "https://#{request.host}/#{request.query_string}" unless request.ssl? end end 
+4
Oct 05 '10 at 8:05
source share

The key problem is that force_ssl.rb does not load and that lib does not load by default in rails 3.1. You must add

 config.autoload_paths += %W(#{config.root}/lib) config.autoload_paths += Dir["#{config.root}/lib/**/"] 

to application.rb

+1
Dec 6 '11 at 20:25
source share



All Articles