How to force an SSL connection with Rails 3, but only when the user is logged in?

I am creating a Rails 3 site that allows a company to update some of its web pages, and I used AuthLogic to take care of user registration and exit.

For most of the traffic to our site, we do not need to use any encryption, because we do not transmit confidential information. However, during login, I find it important to use encryption to protect their password. In addition, from what I understand, it is important that all traffic is encrypted after the user logs in (to avoid theft of their cookies and authentication like them).

There are some helpful tips on using SSL with Rails 3 in the stackoverflow question “ Rails 3 SSL Notrecation ”, but I'm trying to figure out how to encrypt all when a user is logged in (or logged in, etc.), but no , when the user is not logged in. I do not see how conditional routing does this.

+3
source share
2 answers

You can check the protocol in front of the filter:

before_filter do
  unless request.protocol == 'https://'
    redirect_to 'my_page_with_https'
  end
end

But it can be a little too much. I do not know the cost of calling such a filter for each request.

+1
source

, : secure = > true, HTTPS. , ssl ( , ). , .

HTTPS, - gps ssl_requirement.

HTTPS , , , cookie, , HTTPS.

class ApplicationController < ActionController::Base
  def ssl_required?
    # Allow HTTP, but enforce HTTPS for users with the 'ssl' cookie set
    # current_user probably isn't needed here
    Rails.env.production? && (current_user || cookies[:ssl])
  end
end

class AccountsController < ApplicationController
  def login
    if current_user = User.authenticate(user, password)
      # This isn't required for AccountsController,
      # because it enforces HTTPS below.
      cookies[:ssl] = '1'
    end
  end

  def logout
    cookies.delete(:ssl)
  end

  # Enforce HTTPS for the Accounts controller
  def ssl_required?
    Rails.env.production?
  end
end
+1

Source: https://habr.com/ru/post/1787232/


All Articles