ROR – HTTP基本身份验证

参考 Page100

module Backend
  class BaseController < ActionController::Base
    before_action :authenticate

    private

    def authenticate
      authenticate_or_request_with_http_basic do |username, password|
        username == "#{Rails.application.secrets[:name]}" && password == "#{Rails.application.secrets[:password]}"
      end
    end
  end
end

另外一种写法:

module Backend
  class BaseController < ActionController::Base
    http_basic_authenticate_with name: "#{Rails.application.secrets[:name]}", 
      password: "#{Rails.application.secrets[:password]}", if: :need_authentication?

    private

      def need_authentication?
        !Rails.env.development?
      end
  end
end

你可能感兴趣的:(ROR – HTTP基本身份验证)