HTTP Basic Auth for some (not all) controllers

前端 未结 1 634
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-07 17:17

Using Rails 3.2.

I have half a dozen controllers, and want to protect some (but not all) of them with http_basic_authenticate_with.

<
1条回答
  •  臣服心动
    2021-02-07 17:45

    Do it the way Rails does it.

    # rails/actionpack/lib/action_controller/metal/http_authentication.rb
    
    def http_basic_authenticate_with(options = {})
      before_action(options.except(:name, :password, :realm)) do
        authenticate_or_request_with_http_basic(options[:realm] || "Application") do |name, password|
          name == options[:name] && password == options[:password]
        end
      end
    end
    

    All that http_basic_authenticate_with does is add a before_action. You can just as easily do the same yourself:

    # application_controller.rb
    
    before_action :http_basic_authenticate
    
    def http_basic_authenticate
      authenticate_or_request_with_http_basic do |name, password|
        name == 'xxx' && password == 'yyy'
      end
    end
    

    which means you can use skip_before_action in controllers where this behavior isn't desired:

    # unprotected_controller.rb
    
    skip_before_action :http_basic_authenticate
    

    0 讨论(0)
提交回复
热议问题