测试HTTP基本认证Rails中2.2+ [英] Testing HTTP Basic Auth in Rails 2.2+

查看:194
本文介绍了测试HTTP基本认证Rails中2.2+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个API我建立的一部分,有一个用户身份验证方法,该方法成功时,会返回有用的用户信息,API令牌等有效载荷。

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.

在编写处理这个控制器功能测试,我要测试HTTP基本身份验证的问题中运行;我发现,提及以下code应该被用来恶搞头一个认证尝试无数博客:

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)

的问题是,这没有影响; authenticate_with_http_basic 看不到头,因此返回false即使在有效凭据的presence。

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.

我缺少的东西吗?

请注意,该应用程序被冻结到Rails 2.2.2如果是在回答很有用的。

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

推荐答案

我不知道这会有所帮助,但我只是做了我自己的应用程序,这些测试之一,但我用Rails 2.3.2。

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.

在我的情况下,这个缺点是,我忘了放在夹具供用户使用,所以crypted_pa​​ssword不匹配(为什么就没有任何价值仍然是一个谜,我...我猜的Rails没'T运行测试之前清理测试数据库?)

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' => '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

这篇关于测试HTTP基本认证Rails中2.2+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆