【问题标题】:Testing HTTP Basic Auth in Rails 2.2+在 Rails 2.2+ 中测试 HTTP 基本身份验证
【发布时间】:2009-08-11 09:21:52
【问题描述】:

作为我正在构建的 API 的一部分,有一个用户身份验证方法,成功后会返回有用的用户信息、API 令牌等的有效负载。

在为处理此问题的控制器编写功能测试时,我遇到了测试 HTTP Basic auth 的问题;我发现许多博客都提到以下代码应该用于欺骗标头以进行身份​​验证尝试:

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

问题是这没有效果; authenticate_with_http_basic 看不到标头,因此即使存在有效凭据也会返回 false。

我错过了什么吗?

请注意,如果这对回答有用,应用程序将冻结到 Rails 2.2.2。

【问题讨论】:

  • 我只想注意,在 2011 年和 Rails 3.* 中,您引用的代码完美运行。

标签: ruby-on-rails authentication testing http-headers basic-authentication


【解决方案1】:

我不确定这是否有帮助,但我只是在自己的应用程序中进行了其中一项测试,除了我使用的是 Rails 2.3.2。

在我的情况下,陷阱是我忘记为用户添加固定装置,所以 crypted_pa​​ssword 不匹配(为什么它有任何价值对我来说仍然是一个谜......我猜 Rails 没有'在运行测试之前不清理测试数据库?)

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' => 'usbstor\disk&ven_flash&prod_drive_sm_usb20&rev_1100\0000000000000000&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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多