Reputation: 95
In my Rails 4 app, I have a before_action
requiring the user to be logged in, like so:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :require_login
def require_login
unless logged_in?
flash[:alert] = "You must be logged in to access this section."
redirect_to login_path
end
end
def logged_in?
# more logic
end
end
When I visit example.com
without being logged in, I get redirected to example.com/login
as expected. However, I see this error in the console:
The page at 'https://example.com/login' was loaded over HTTPS, but displayed
insecure content from 'http://example.com/login': this content should also
be loaded over HTTPS.
The network tab appears to indicate that my redirect_to
is pointing me to HTTP
and not HTTPS
. When it hits the HTTP, it then automatically redirects to HTTPS
.
Request URL:http://example.com/login
Request Method:GET
Status Code:301 Moved Permanently
# In the response headers:
Location:https://example.com/login
Is there a way to tell the redirect_to
that it should use HHTPS
instead of HTTP
, or is this an nginx config? I thought that using login_path
as opposed to login_url
would fix the issue since it should be relative to the base, but that didn't seem to work.
Update:
I thought about using force_ssl
as well but was worried that I was taking a hammer to a push pin. Feel free to correct me if I'm mistaken.
Upvotes: 3
Views: 2781
Reputation: 33626
Use #force_ssl
:
class ApplicationController < ActionController::Base
force_ssl # use HTTPS for all actions
protect_from_forgery with: :exception
before_action :require_login
def require_login
unless logged_in?
flash[:alert] = "You must be logged in to access this section."
redirect_to login_path
end
end
def logged_in?
# more logic
end
end
Upvotes: 1
Reputation: 9049
In your application.rb
(or environment.rb
), you could set
config.force_ssl = true
This would make Rails use a secure end-point always.
Upvotes: 6