23

What is the difference between

http_basic_authenticate_with()

and

authenticate_or_request_with_http_basic()

methods?

Thanks for your full explanation.

user664833
  • 18,397
  • 19
  • 91
  • 140
Douglas
  • 5,229
  • 3
  • 43
  • 54

1 Answers1

28

From what I can understand from the docs, http_basic_authenticate_with acts as a before filter which accepts a name and password such as

http_basic_authenticate_with :name => "dhh", :password => "secret", :except => :index

Whereas authenticate_or_request_with_http_basic accepts a block allowing for you to insert some code to determine whether they should be authenticated (documentation). E.g.

before_filter :authenticate

def authenticate
  authenticate_or_request_with_http_basic('Administration') do |username, password|
    ActiveSupport::SecurityUtils.secure_compare(username, "admin") &&
    ActiveSupport::SecurityUtils.secure_compare(password, "password")
  end
end
Capripot
  • 1,354
  • 16
  • 26
chrisbulmer
  • 1,237
  • 8
  • 15
  • 1
    And **to test at the controller level**, use `@request.env['HTTP_AUTHORIZATION'] = 'Basic ' + Base64::encode64('username:password')` then `get :your_action`. Ref: http://apidock.com/rails/ActionController/HttpAuthentication/Basic/ControllerMethods/authenticate_or_request_with_http_basic#197-Testing-protected-controllers – user664833 Feb 03 '14 at 22:43
  • `http_basic_authenticate_with` actually calls `authenticate_or_request_with_http_basic` internally. See the [source](https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/metal/http_authentication.rb#L69). – mlovic Jan 10 '17 at 17:25