Skip to content

Instantly share code, notes, and snippets.

@denisahearn
Created October 12, 2011 19:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save denisahearn/1282275 to your computer and use it in GitHub Desktop.
Save denisahearn/1282275 to your computer and use it in GitHub Desktop.
Testing HTTP Digest Authentication in Rails 3
# 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
@frankieroberto
Copy link

This works for me within functional tests (ActionController::TestCase) but not within integration tests (ActionDispatch::IntegrationTest).

Any ideas why that might be?

@natebird
Copy link

That is because the method is wrapped in ActionController::TestCase. You can pull the method out and you can include it in other tests.

@murbanski
Copy link

RSpec 3.1 and Rails 4 HTTP Digest Auth testing: https://gist.github.com/murbanski/6b971a3edc91b562acaf

@rusanu
Copy link

rusanu commented Feb 5, 2016

I packed similar implementation into a gem for reuse https://github.com/rusanu/http_digest_test

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment