【问题标题】:Writing a Test/Method for HTTP Digest Authentication为 HTTP 摘要式身份验证编写测试/方法
【发布时间】:2025-11-26 22:30:02
【问题描述】:

我将如何编写一个用于 rspec 测试的方法来访问需要用户名和密码以进行 HTTP Digest 身份验证的页面。比如这个测试...

it "edit" do
  http_login
  post :edit, id: @post
  assigns[:post].should eq(@post)
end

需要http_login 方法是这样的......

def http_login

 user = {"username" => 
 Digest::MD5.hexdigest(["username","Application","password"].join(":"))} 

 request.env['HTTP_AUTHORIZATION'] = 
 ActionController::HttpAuthentication::Digest.encode_credentials(?,?,?,?)
end

我的问题是我在四个参数中为编码凭据添加了什么。参数将是 http_method, credentials, password, password_is_ha1,但我不确定如何编写 http_methodcredentials 以在测试中实现。

【问题讨论】:

  • (不,这是基本的)。看起来在这里得到回答*.com/questions/3768718/…
  • 那是基本的http认证。我正在做摘要式 http 身份验证。
  • 也许是这个? gist.github.com/1282275
  • 嗯.. 今晚晚些时候我会测试一下。它看起来很容易使用。如果它有效,我会通知您,如果您将其作为答案发布,我会为您提供答案。

标签: ruby-on-rails ruby-on-rails-3 rspec digest-authentication


【解决方案1】:

这里的解决方案:https://gist.github.com/1282275

在这里复制以供后代使用

# Adds support for http digest authentication in Rails 3  
# Inspired by: http://lightyearsoftware.com/2009/04/testing-http-digest-authentication-in-rails/
# Place this code in test/test_helper.rb
# In your test, call authenticate_with_http_digest prior to calling get, post, put or delete  
# Tested with Rails 3.0.7

class ActionController::TestCase
  require 'digest/md5'

  def authenticate_with_http_digest(user = API_USERNAME, password = API_PASSWORD, realm = API_REALM)
    ActionController::Base.class_eval { include ActionController::Testing }

    @controller.instance_eval %Q(
      alias real_process_with_new_base_test process_with_new_base_test

      def process_with_new_base_test(request, response)
        credentials = {
      :uri => request.url,
      :realm => "#{realm}",
      :username => "#{user}",
      :nonce => ActionController::HttpAuthentication::Digest.nonce(request.env['action_dispatch.secret_token']),
      :opaque => ActionController::HttpAuthentication::Digest.opaque(request.env['action_dispatch.secret_token'])
        }
        request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Digest.encode_credentials(request.request_method, credentials, "#{password}", false)

        real_process_with_new_base_test(request, response)
      end
    )
  end
end

【讨论】:

  • 仅供参考,如果有人想将其放入 rspec,只需从答案中获取方法并将其放入您的 rpsec 帮助文件中。
【解决方案2】:

这是 RSpec 3.1 和 Rails 4 HTTP Digest Auth 测试的解决方案:https://gist.github.com/murbanski/6b971a3edc91b562acaf

【讨论】: