Rails 3.1 Force Regular HTTP

半城伤御伤魂 提交于 2019-11-28 20:43:17

The code for Force SSL is pretty easy to read.

https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/force_ssl.rb

It doesn't seem to do the reverse and force http to be used. It provides the only and except options to control which actions and controllers SSL is to be required for, but doesn't provide a way to force HTTP to be used instead of https.

Joost Baaij

What Justice said. Some people feel strongly about browsing with SSL for everything. It's now trivial to snoop non-SSL sessions, so you should go out of your way to accomodate people who want to use it.

However.

It should be fairly easy to accomplish using a before_filter:

class ApplicationController < ActionController::Base
  before_filter do
    if request.ssl? && Rails.env.production?
      redirect_to :protocol => 'http://', :status => :moved_permanently
    end
  end
end

To use force_non_ssl the exact same way as force_ssl check this Rails Concern: https://gist.github.com/joost/6989118

Accepts options like:

force_non_ssl only: :show
force_non_ssl except: :show, notice: "Hi this is now insecure :)"

I simplified joost's code to all I needed. Thanks joost

if request.ssl?
  options = {
    :protocol => 'http://',
    :host     => request.host,
    :path     => request.fullpath,
    :status   => :moved_permanently
  }
  non_secure_url = ActionDispatch::Http::URL.url_for(options.slice(*URL_OPTIONS))
  redirect_to non_secure_url, options.slice(*REDIRECT_OPTIONS)
end

For those who just need to disable force_ssl behaviour on their whole app for a short time on local machine like me, you can simply do this in your ApplicationController:

def self.force_ssl *a
  warn "force_ssl disabled globally"
end

Just make sure not to commit it to your codebase.

Why would you ever want to force HTTP over HTTPS?

A lot of us out here browse with SSL everywhere. Please don't put the rest of us at risk simply because you don't like helping us out with our own security.

For most of us, security is important, even if most of us don't understand its importance or know how to obtain it. For some of us, security is life and death critical.

Some pages must be served over SSL. Although, in my view, if any part of your site requires being served over SSL, then the entire site requires it (a MITM can change the link to the SSL page as it is rendered on the non-SSL page to point to a non-SSL proxy that the MITM controls). No page ever requires being served without SSL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!