Тестирование дайджест-аутентификации HTTP в Rails 4

В Rails 3 мы использовали этот приятный небольшой хак (по крайней мере, он был включен и легко использовался повторно) - Написание теста/метода для дайджест-аутентификации HTTP

Однако этот метод (process_with_new_base_test) полностью отсутствует в Rails 4 (master). Кто-нибудь знает, как правильно протестировать дайджест-аутентификацию в Rails 4?

Rails 4.0.b1 ActionController::Testing

Rails 3.2.x ActionController::Testing


person Nate Bird    schedule 19.04.2013    source источник
comment
Привет, Нейт, ты в конце концов нашел какую-нибудь полезную документацию или ссылки по этой проблеме?   -  person dodgerogers747    schedule 01.12.2013


Ответы (2)


Я была такая же проблема. Я прочитал тестовые примеры Rails 4 и построил следующее решение. Он не идеален ни при каких обстоятельствах, но работает в моей тестовой среде. Это вспомогательное решение для оригинального вспомогательного метода authenticate_with_http_digest.

Суть здесь: https://gist.github.com/illoyd/9429839

И для потомков:

# This should go into spec/support/auth_spec_helpers.rb (if you are using RSpec)
module AuthSpecHelpers

  ##
  # Convenience method for setting the Digest Authentication details.
  # To use, pass the username and password.
  # The method and target are used for the initial request to get the digest auth headers. These will be translated into 'get :index' for example.
  # The final 'header' parameter sets the request's authentication headers.
  def authenticate_with_http_digest(user, password, method = :get, target = :index, header = 'HTTP_AUTHORIZATION')
    @request.env[header] = encode_credentials(username: user, password: password, method: method, target: target)
  end

  ##
  # Shamelessly stolen from the Rails 4 test framework.
  # See https://github.com/rails/rails/blob/a3b1105ada3da64acfa3843b164b14b734456a50/actionpack/test/controller/http_digest_authentication_test.rb
  def encode_credentials(options)
    options.reverse_merge!(:nc => "00000001", :cnonce => "0a4f113b", :password_is_ha1 => false)
    password = options.delete(:password)

    # Perform unauthenticated request to retrieve digest parameters to use on subsequent request
    method = options.delete(:method) || 'GET'
    target = options.delete(:target) || :index

    case method.to_s.upcase
    when 'GET'
      get target
    when 'POST'
      post target
    end

    assert_response :unauthorized

    credentials = decode_credentials(@response.headers['WWW-Authenticate'])
    credentials.merge!(options)
    path_info = @request.env['PATH_INFO'].to_s
    uri = options[:uri] || path_info
    credentials.merge!(:uri => uri)
    @request.env["ORIGINAL_FULLPATH"] = path_info
    ActionController::HttpAuthentication::Digest.encode_credentials(method, credentials, password, options[:password_is_ha1])
  end

  ##
  # Also shamelessly stolen from the Rails 4 test framework.
  # See https://github.com/rails/rails/blob/a3b1105ada3da64acfa3843b164b14b734456a50/actionpack/test/controller/http_digest_authentication_test.rb
  def decode_credentials(header)
    ActionController::HttpAuthentication::Digest.decode_credentials(header)
  end

end

# Don't forget to add to rspec's config (spec/spec_helper.rb)
RSpec.configure do |config|
  # Include auth digest helper
  config.include AuthSpecHelpers, :type => :controller
end

Удачного тестирования.

person Ian Lloyd    schedule 08.03.2014

Вот более простая в использовании версия: https://gist.github.com/murbanski/6b971a3edc91b562acaf

person Marcin Urbanski    schedule 29.10.2014
comment
Спасибо за чистый ответ. И совместим с Rspec 3.1. :-) - person Nate Bird; 30.10.2014