Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
778 views
in Technique[技术] by (71.8m points)

authentication - Testing HTTP Basic Auth in Rails 2.2+

As part of an API I am building, there is a user authentication method which upon success, returns a payload of useful user information, API token, etc.

In writing functional tests for the controller that handles this, I am running in to an issue testing HTTP Basic auth; I have found numerous blogs that mention the following code should be used to spoof headers for an authentication attempt:

@request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(email, pass)

The issue is that this has no effect; authenticate_with_http_basic does not see the headers and therefore is returning false even in the presence of valid credentials.

Am I missing something?

Note that the app is frozen to Rails 2.2.2 if that is useful in answering.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not sure if this helps, but I just made one of these tests in my own application, except I'm using Rails 2.3.2.

In my case, the pitfall was that I had forgotten to put in the fixtures for users, so the crypted_password didn't match (why it had any value at all is still a mystery to me... I guess Rails didn't clean the test database before running the test?)

class DonglesControllerTest < ActionController::TestCase
  fixtures :users

  test "index api" do
    @request.env['HTTP_AUTHORIZATION'] = encode_credentials('one', 'one')

    get(:index, { :name_contains => 'XXXX0001', :format => 'json' })

    assert_equal 'application/json', @response.content_type
    dongles = ActiveResource::Formats::JsonFormat.decode(@response.body)

    expected_dongles = [
      { 'id' => 1,
        'name' => 'XXXX0001',
        'key_id' => 'usbstordisk&ven_flash&prod_drive_sm_usb20&rev_1100000000000000000&0' }
    ]

    assert_equal expected_dongles, dongles
  end

  private

  # verbatim, from ActiveController's own unit tests
  def encode_credentials(username, password)
    "Basic #{ActiveSupport::Base64.encode64("#{username}:#{password}")}"
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...