Redirect to SSL in Rails applications

I’ve looked at the various ssl_requirement repositories out there. I concluded the most modern and maintained version is yardstick’s which is released as a gem called sslrequirement, but I’ve failed to use it properly. So I just did it by hand.

First, we need a simple method that will let us know whether SSL is enabled or not. We don’t want to redirect to SSL in development mode because it’ll fail. In the application controller I’ve created:

  def ssl_enabled?
    !(Rails.env.development? || Rails.env.test?)
  end

Switching to SSL is not only a matter of redirecting. If you show a login or signup form in your homepage, like I do in Restraq, you want that to point to https even if the page was loaded as http. So I’ve added this helper method in the application controller:

  def https
    ssl_enabled? ? "https://" : "http://"
  end
  helper_method :https

and then for the forms I just do this:

form_for ..., :url => session_url(resource_name, :protocol => https)

and

form_for ..., :url => registration_url(resource_name, :protocol => https)

And then the redirection part, which is a before filter in the application controller because I want to redirect when hitting Devise controllers:

  def enforce_ssl_if_needed
    if request.protocol == "http://" && ssl_enabled? &&
            (controller_name == "registrations" || controller_name == "sessions")
      redirect_to :protocol => https
    end
    return true
  end

and that’s it. I’m not actually testing it yet. For a similar solution with tests you might want to check out SSLShopper’s article about this.

Advertisements

3 thoughts on “Redirect to SSL in Rails applications

  1. Thanks for this useful article. It helps me a lot.
    You might wan to use following code to redirect.
    redirect_to params.merge(:protocol => ‘https’)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s