Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force SSL using ssl_requirement in Rails 2 app

I have a Rails application which need to run under SSL. I tried ssl_requirement but seems I have to type in all the actions in every controllers.

Is there any method that I can add a before_filter in application controller with ssl_requirement, so that the apps will redirect to https automatically when user request is in http?

Thanks all. :)

like image 500
Victor Lam Avatar asked Oct 05 '10 07:10

Victor Lam


3 Answers

Use a Rack Middleware.

# 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"
like image 133
Simone Carletti Avatar answered Oct 20 '22 00:10

Simone Carletti


You can try test if request is in ssl or not in a before_filter 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
like image 44
shingara Avatar answered Oct 20 '22 01:10

shingara


The key problem is that force_ssl.rb isn't being loaded and that lib isn't loaded by default in rails 3.1. You have to add

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

to application.rb

like image 31
Alex Fishman Avatar answered Oct 20 '22 00:10

Alex Fishman