I have an HTTP and HTTPS version of my Ruby on Rails running, and if someone accesses through the HTTP one, I want to automatically reload the HTTPS version.
I have done this before on Apache with .httaccess. How can I do it on Rails?
Thanks
In your production.rb file (or whichever env you are forcing ssl) add
config.force_ssl = true
You can also achieve that by:
class ApplicationController < ActionController::Base
force_ssl if: :ssl_enabled?
private
def ssl_enabled?
%w(staging production).include?(Rails.env)
end
end
You can achieve it by putting the below code in config/applcation.rb
#config/application.rb
config.force_ssl = true
Check this blog and this SO post for more info.
Related
I'm working on a platform built with Ruby(v2.1.2) on Rails(v4.1.6) and we're trying to enforce SSL. How do I go about doing this?
So far, I have force_ssl
# application_controller.rb
force_ssl if: :ssl_configured?
def ssl_configured?
return false if params[:controller] == 'high_voltage/pages'
(Rails.env.development? || Rails.env.test?) ? false : true
end
Which seems to work because when I try to do http://www.somecoolsite.com, it then automatically becomes https://www.somecolesite.com.
However, if I try to submit a JSON post request to the API portion of our platform, and the URL is http://, the post request is somehow returning the results of a get request instead. But when I change the URL to https://, the post request works as expected. How would I go about fixing this so that if a client accidentally submits their request as http://, it is rewritten to https://?
Thanks!
Have you looked at using config.force_ssl = true in your production environment config? This is far more all-encompassing, but can lead to other issues as well.
I am using rails 4.1.1 and ActionMailer::Preview for previewing emails. In development environment everything is working excellent.
But in production environment the preview routes are not accessible. I store the previews in test/mailers/previews/
Is is possible to enable them for production?
In addition to this:
config.action_mailer.show_previews = true
you will also need to set
config.consider_all_requests_local = true
in your environment for the preview routes to be accessible. This has other implications as well (see https://stackoverflow.com/a/373135/1599045) so you likely don't want to enable this in production. However, if you have a custom environment that's not development, the combination of those two should get things working.
EDITED TO ADD:
The original question was for rails 4.1.1, which doesn't have config.action_mailer.show_previews available. To get ActionMailer previews working in non-development environments in rails 4.1.1, you need to first add some routes to config/routes.rb (in this case, my environment is named custom):
if Rails.env.custom?
get '/rails/mailers' => "rails/mailers#index"
get '/rails/mailers/*path' => "rails/mailers#preview"
end
Then you need to autoload the libraries needed in your environment's config file (in my case, config/environments/custom.rb):
config.action_mailer.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/test/mailers/previews" : nil
config.autoload_paths += [config.action_mailer.preview_path]
This seems to perform the same task as config.action_mailer.show_previews does.
As with 4.2, you will still need to adjust the local request configuration as above depending on whether your custom environment is being used locally or on a server.
To do it without opening a big security hole:
production.rb
MyApp::Application.configure do
config.action_mailer.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/spec/mailer_previews" : nil
config.autoload_paths += [config.action_mailer.preview_path]
routes.append do
get '/rails/mailers' => "rails/mailers#index"
get '/rails/mailers/*path' => "rails/mailers#preview"
end
end
class ::Rails::MailersController
before_filter :authenticate_admin!
def local_request?
true
end
private
def authenticate_admin!
...
end
end
It's possible to enable previews in production by config.action_mailer.show_previews = true as the best answer says.
I just want to add how you can render previews in iframe within your own admin area, eg. in active admin (Rails 5.1)
And also I found out that it is not so hard to write your own email previews administration, and don't use rails standard previews at all. You can then add your own features such as changing preview parameters or Send button to see this email in your phone.
From Rails 4.2 you can use the flag in production.rb (or other custom enviroment):
config.action_mailer.show_previews = true
I haven't found anything similar in Rails 4.1.
Update:
If Rspec used, for example, there will be need to add the path:
config.action_mailer.preview_path = "#{Rails.root}/spec/mailers/previews"
Default path is "#{Rails.root}/test/mailers/previews".
And no need to touch config.consider_all_requests_local
Here's what I did for Rails 5.2:
production.rb
config.action_mailer.show_previews = true
config.action_mailer.preview_path ||= defined?(Rails.root) ? "#{Rails.root}/spec/mailers/previews" : nil
class ::Rails::MailersController
include ::ApplicationController::Authorization
before_action :require_admin
end
Assuming your ApplicationController::Authorization module has the code for require_admin. I preferred this approach rather than rewriting my authorization code. Remembering to include the :: in front was tricky, because saying include ApplicationController::... will look within the Rails::MailersController namespace.
I am trying to test a responsive design. I am using Rails 4.
I know it sets 'X-Frame-Options' to SAME ORIGIN. So I overrided it in development.rb using
config.action_dispatch.default_headers = {
'X-Frame-Options' => 'ALLOWALL'
}
and it worked. I checked out the network request in the Chrome console and it is as follows:
But still websites like responsive.is and responsinator.com give me below error:
Refused to display 'http://localhost:3000/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'. about:blank:1
Whats going on??
Try just to delete this header 'X-Frame-Options'.
Maybe this way in controller:
before_filter :allow_iframe_requests
...
def allow_iframe_requests
response.headers.delete('X-Frame-Options')
end
I had the same problem as you, and searched for a solution to this problem all night.
I finally found out why it happens. It's because of the Chrome cache.
You can see the header['X-Frame-Options'] is ALLOWALL but it doesn't work.
Just try to open a "New Incognito Window" and go the same page and it works!
This problem only happened in development mode in my test. It worked fine in production mode.
Rails 4 added a default X-Frame-Options HTTP header value of SAMEORIGIN. This is good for security, but when you do want your action to be called in an iframe, you can do this:
To Allow all Origins:
class MyController < ApplicationController
def iframe_action
response.headers.delete "X-Frame-Options"
render_something
end
end
To Allow a Specific Origin:
class MyController < ApplicationController
def iframe_action
response.headers["X-FRAME-OPTIONS"] = "ALLOW-FROM http://some-origin.com"
render_something
end
end
Use :after_filter
When you need to use more than one of your action in an iframe, it's a good idea to make a method and call it with :after_filter:
class ApplicationController < ActionController::Base
private
def allow_iframe
response.headers.delete "X-Frame-Options"
end
end
Use it in your controllers like this:
class MyController < ApplicationController
after_filter :allow_iframe, only: [:basic_embed, :awesome_embed]
def basic_embed
render_something
end
def awesome_embed
render_something
end
# Other Actions...
end
Do a Hard-Refresh in your browser, or use another browser to view changes
Via: Rails 4: let specific actions be embedded as iframes
When 'Load denied by X-Frame-Options' using Heroku & Firefox
I had a similar issue where I kept getting this error only on Firefox. I had a PHP web page hosted # MochaHost serving a Rails app hosted # Heroku (so RoR app has a page with an iframe which is pointing to the PHP web page and this working on all browsers except on Firefox).
I was able to solve the problem by setting a default header for all of my requests in the specific environment file:
# config/enviroments/production.rb
config.action_dispatch.default_headers = { 'X-Frame-Options' => 'ALLOWALL' }
Edit
(as sheharyar suggested)
Ideally, you shouldn't set a default header and do this only for actions that have to be rendered in an iFrame. If your entire app is being served inside an iFrame, you should explicitly mention the Origin:
# config/enviroments/production.rb
config.action_dispatch.default_headers = { 'X-Frame-Options' => 'ALLOW-FROM http://some-origin.com' }
Try ALLOW-FROM http://example.com instead? ALLOWALL might be ok in Chrome if you have a sufficiently new version of Chrome [2]
[1] https://developer.mozilla.org/en-US/docs/HTTP/X-Frame-Options
[2] https://stackoverflow.com/a/16101968/800526
I found another cause for this. Assuming the ALLOWALL or similar fix is implemented, the next gotcha is attempting to use http content in a https website which causes security risks and is blocked by mozilla, IE and probably other browsers. It took me 6 hours to identify this, hopefully by sharing I can reduce someones pain...
It can be checked by:
using your browser web-tools which should display an error.
web logs will lack any connection with your supplying site.
replace your contents url with a banks https home page should demonstrate the iframe otherwise works.
The solution is to ask the source if they have https content or find another supplier.
ref:
https://developer.mozilla.org/en/docs/Security/MixedContent
https://developer.mozilla.org/en-US/docs/Security/MixedContent/How_to_fix_website_with_mixed_content
I just wanted to give an updated answer here on dealing with embedding a Rails app in an iframe.
Its not a great idea to simply delete X-Frame-Options headers without having some other kind of security enforced to prevent against Clickjacking (which is the vulnerability X-Frame-Options is largely trying to protect you from).
The problem is that the X-Frame-Options 'ALLOW-FROM' option is not accepted on most major browsers anymore.
As of writing this, May 28th 2020, the best solution for preventing Clickjacking and hosting your app in an iframe is to implement a Content-Security-Policy and set a 'frame_ancestors' policy. The 'frame_ancestors' key designates what domains can embed your app as an iframe. Its currently supported by major browsers and overrides your X-Frame-Options.
You can set up a Content-Security-Policy with Rails 5.2 in an initializer (example below), and for Rails < 5.2 you can use a gem like the Secure Headers gem: https://github.com/github/secure_headers
You can also override the policy specifications on a controller/action basis if you'd like.
Content-Security-Policies are great for advanced security protections. Check out all the things you can configure in the Rails docs: https://edgeguides.rubyonrails.org/security.html
A Rails 5.2 example for a Content-Security-Policy:
# config/initializers/content_security_policy.rb
Rails.application.config.content_security_policy do |policy|
policy.frame_ancestors :self, 'some_website_that_embeds_your_app.com'
end
An example of a controller specific change to a policy:
# Override policy inline
class PostsController < ApplicationController
content_security_policy do |p|
p.frame_ancestors :self, 'some_other_website_that_can_embed_posts.com'
end
end
If you want to have this change take effect in all environments, place it in application.rb.
Is there an easy way to enable SSL on the entire app?
I'm using rails 2.3.8
By default, all of your controllers should inherit from ApplicationController.
ssl_required is actually backed by a protected method called ssl_required? which determines whether SSL is required for a given action. This implementation will make SSL always required in the production environment (but not otherwise, so you can still do development as usual).
class ApplicationController < ActionController::Base
# (... other stuff ...)
protected
def ssl_required?
Rails.env.production?
end
end
Depending on your environment, it may also be possible for the upstream server to only be available via HTTPS (e.g. if you're using Apache, you could configure it not to serve your application over port 80). This depends on your server setup.
In Rails 5 you can do this in your application configuration:
So if you want to disable it for your entire application you can just add this to your config/application.rb:
...
config.force_ssl = true
...
Or if you want to configure it differently for different environments:
config/production.rb
...
config.force_ssl = true
...
config/development.rb
...
config.force_ssl = false
...
I'm maintaining a Ruby on Rails site and I'm confused as to how to perform redirects to relative URLs using the https protocol.
I can successfully create a redirect to a relative URL using http, for example:
redirect_to "/some_directory/"
But I cannot discern how to create a redirect to a URL using the https protocol. I have only been able to do so by using absolute URLS, for example:
redirect_to "https://mysite.com/some_directory/"
I would like to keep my code clean, and using relative URLs seems like a good idea. Does anyone know how to achieve this in Rails?
The ActionController::Base#redirect_to method takes an options hash, one of the parameters of which is :protocol which allows you to call:
redirect_to :protocol => 'https://',
:controller => 'some_controller',
:action => 'index'
See the definition for #redirect_to and #url_for for more info on the options.
Alternatively, and especially if SSL is to be used for all your controller actions, you could take a more declarative approach using a before_filter. In ApplicationController you could define the following method:
def redirect_to_https
redirect_to :protocol => "https://" unless (request.ssl? || request.local?)
end
You can then add filters in your those controllers which have actions requiring SSL, e.g:
class YourController
before_filter :redirect_to_https, :only => ["index", "show"]
end
Or, if you require SSL across your entire app, declare the filter in ApplicationController:
class ApplicationController
before_filter :redirect_to_https
end
If you want your entire application to be served over https then since Rails 4.0 the best way to do this is to enable force_ssl in the configuration file like so:
# config/environments/production.rb
Rails.application.configure do
# [..]
# Force all access to the app over SSL, use Strict-Transport-Security,
# and use secure cookies.
config.force_ssl = true
end
By default this option is already present in config/environments/production.rb in in newly generated apps, but is commented out.
As the comment says, this will not just redirect to https, but also sets the Strict-Transport-Security header (HSTS) and makes sure that the secure flag is set on all cookies. Both measures increase the security of your application without significant drawbacks. It uses ActionDispatch:SSL.
The HSTS expire settings are set to a year by default and doesn't include subdomains, which is probably fine for most applications. You can configure this with the hsts option:
config.hsts = {
expires: 1.month.to_i,
subdomains: false,
}
If you're running Rails 3 (>=3.1) or don't want to use https for the entire application, then you can use the force_ssl method in a controller:
class SecureController < ApplicationController
force_ssl
end
That's all. You can set it per controller, or in your ApplicationController. You can force https conditionally using the familiar if or unless options; for example:
# Only when we're not in development or tests
force_ssl unless: -> { Rails.env.in? ['development', 'test'] }
You're probably better off using ssl_requirement and not caring if a link or redirect is or isn't using https. With ssl_requirement, you declare which actions require SSL, which ones are capable of SSL and which ones are required not to use SSL.
If you're redirecting somewhere outside of your Rails app, then specifying the protocol as Olly suggests will work.
If you want to globally controll the protocol of urls generated in controllers, you can override the url_options method in you application controller. You could force the protocol of the generated urls depending on the rails env like so :
def url_options
super
#_url_options.dup.tap do |options|
options[:protocol] = Rails.env.production? ? "https://" : "http://"
options.freeze
end
end
this example works in rails 3.2.1, i'm not exactly sure for earlier or future versions.
This answer is somewhat tangential to the original question, but I record it in case others end up here in similar circumstances to myself.
I had a situation where I needed to have Rails use https proto in url helpers etc. even though the origin of all requests is unencrypted (http).
Now, ordinarily in this situation (which is normal when Rails is behind a reverse proxy or load balancer etc.), the x-forwarded-proto header is set by the reverse proxy or whatever, so even though requests are unencrypted between the proxy & rails (probably not advisable in production by the way) rails thinks everything is in https.
I needed to run behind an ngrok tls tunnel. I wanted to have ngrok terminate the tls with letsencrypt certificates I specified. However when it does so, ngrok does not offer the ability to customize headers, including setting x-forwarded-proto (although this feature is planned at some point in the future).
The solution turned out to be quite simple: Rails does not depend on either the protocol of the origin or whether x-forwarded-proto is set directly, but on the Rack env var rack.url_scheme. So I just needed to add this Rack middleware in development:
class ForceUrlScheme
def initialize(app)
#app = app
end
def call(env)
env['rack.url_scheme'] = 'https'
#app.call(env)
end
end
In Rails 4 one can use the force_ssl_redirect before_action to enforce ssl for a single controller. Please note that by using this method your cookies won't be marked as secure and HSTS is not used.
If you want to force ALL traffic via https, then the best way in Rails 6 is to configure production.rb with:
config.force_ssl = false
If you need a more flexible solution, you can handle it with a simple before_action filter:
class ApplicationController < ActionController::Base
include SessionsHelper
include LandingpageHelper
include ApplicationHelper
include UsersHelper
include OrganisationHelper
before_action :enforce_ssl, :except => [:health]
def enforce_ssl
if ENV['ENFORCE_SSL'].to_s.eql?('true') && !request.ssl?
redirect_to request.url.gsub(/http/i, "https")
end
end
end
If you run your application on AWS ECS Fargate with health checks, then you need a more flexible solution because the health check from the AWS target group is not invoked via https. Of course, you want the health check to work and at the same time, you want to force SSL for all other controller methods.
The ENFORCE_SSL is just an environment variable that turns this feature on/off.
Add protocol to ..._url:
redirect_to your_url(protocol: 'https')
or with subdomain:
redirect_to your_url(protocol: 'https', subdomain: 'your_subdomain')
Relative URLs, by definition, use the current protocol and host. If you want to change the protocol being used, you need to supply the absolute URL. I would take Justice's advice and create a method that does this for you:
def redirect_to_secure(relative_uri)
redirect_to "https://" + request.host + relative_uri
end
Open the class that has redirect_to and add a method redirect_to_secure_of with an appropriate implementation. Then call:
redirect_to_secure_of "/some_directory/"
Put this method in the lib directory or somewhere useful.