Set ssl_allowed/ssl_required for all pages in Rail

2019-08-12 16:55发布

I found that AJAX calls were not working on my Rails site when a page was using SSL/HTTPS. I worked around this by adding

ssl_allowed :action1, :action2, :actionN

to the controllers involved.

I foresee this being a pain and prone to bugs in the future, as I'll indubitably forget to add an action to the ssl_allowed list.

Is there a way to turn on ssl_allowed/ssl_required globally in the [ssl_requirement][1] gem, for all actions of every controller in my site? I tried adding the following to ApplicationController, but that did not work:

ssl_allowed :all

2条回答
地球回转人心会变
2楼-- · 2019-08-12 17:43

If you'd rather not depend on a forked plugin, you can override ssl_allowed? in your controller:

 class ApplicationController < ActionController::Base
    ...
    private

    def ssl_allowed?
       true
    end
 end

EDIT: This does not do what I thought it did. Instead of disabling redirects to http for pages that are not specified ssl_required, it short circuts the whole redirect process to do nothing. This is very bad. The code:

 def ensure_proper_protocol
   return true if ssl_allowed?

   if ssl_required? && !request.ssl?
     redirect_to "https://" + request.host + request.request_uri
     flash.keep
     return false
   elsif request.ssl? && !ssl_required?
     redirect_to "http://" + request.host + request.request_uri
     flash.keep
     return false
   end
 end

Adding the ssl_allowed? method like this would only be the answer if the code instead read:

def ensure_proper_protocol
  if ssl_required? && !request.ssl?
    redirect_to "https://" + request.host + request.request_uri
    flash.keep
    return false
  elsif request.ssl? && !ssl_required? && !ssl_allowed?
    redirect_to "http://" + request.host + request.request_uri
    flash.keep
    return false
  end
end
查看更多
叛逆
3楼-- · 2019-08-12 17:51

I found grosser's ssl_requirement fork at github (link) which enables "ssl_allowed :all" and replaced my copy of the gem with that version. Now I'm using "ssl_allowed :all" in my ApplicationController and nowhere else. Exactly what I wanted.

查看更多
登录 后发表回答