Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accept only HTTPS requests in Ruby on Rails

For the some actions, I would like to accept only HTTPS request.
This is my first code, but I think there is a better way.

before_filter :reject_http_request, :only => [:fucntion_a, :function_b]

def reject_http_request
  scheme = request.protocol.to_s.downcase
  if scheme == 'http://'
    raise AccessDeniedException.new("Not allowed protocol scheme")
  end
  true
end

How can I improve this code?

like image 365
Benjamin Avatar asked Apr 23 '26 05:04

Benjamin


2 Answers

You can do this at the Rack level with the rack-ssl-enforcer gem. It's configurable to allow exclusion of specific paths, hosts, and methods.

If it meets your needs, I'd recommend doing this over rolling your own solution. We currently use it in production and it works great.

like image 76
Chris Schmich Avatar answered Apr 24 '26 20:04

Chris Schmich


For forcing SSL for a particular action, you can use force_ssl.
For the entire app, you can just do: config.force_ssl = true in your environment.rb file.
Read more here.

like image 44
wless1 Avatar answered Apr 24 '26 21:04

wless1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!