Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvandervossen/2764167 to your computer and use it in GitHub Desktop.
Save tvandervossen/2764167 to your computer and use it in GitHub Desktop.
Testing HTTP Digest Authentication in Rails 3
# Add this to test/test_helper.rb
# Allow http digest authentication in functional tests, based on https://gist.github.com/1282275
# Call authenticate_with_http_digest(user, realm, digest) or authenticate_with_http_digest(user, realm, password, false) before you perform a request
class ActionController::TestCase
require 'digest/md5'
def authenticate_with_http_digest(user, realm, password, password_is_ha1 = true)
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}", #{password_is_ha1})
real_process_with_new_base_test(request, response)
end
)
end
end
@tvandervossen
Copy link
Author

Change arguments to accept the digest instead of the plain-text password by default

@natebird
Copy link

natebird commented Dec 6, 2012

I just started getting an error message using this code snippet in my tests. Any ideas?

Here is the error:

NameError: undefined method `process_with_new_base_test' for class `AuthController`

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