Skip to content

Instantly share code, notes, and snippets.

@pacoguzman
Created March 17, 2012 09:49
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 pacoguzman/2057192 to your computer and use it in GitHub Desktop.
Save pacoguzman/2057192 to your computer and use it in GitHub Desktop.
Test examples of http digest authentication that doesn't works
require 'isolation/abstract_unit'
require 'rack/test'
require 'digest/md5'
require 'action_controller'
require 'rails'
module ApplicationTests
class HttpDigestAuthenticationTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Isolation
include Rack::Test::Methods
def setup
build_app
boot_rails
FileUtils.rm_rf "#{app_path}/config/environments"
end
def teardown
teardown_app
end
def app
@app ||= ::Rails.application
end
define_method :simple_controller do
class ::OmgController < ActionController::Base
REALM = "SuperSecret"
USERS = {"dhh" => "secret", #plain text password
"dap" => Digest::MD5.hexdigest(["dap", REALM, "secret"].join(":"))} #ha1 digest password
before_filter :authenticate
def index
render :text => "Hello Secret"
end
private
def authenticate
authenticate_or_request_with_http_digest(REALM) do |username|
USERS[username]
end
end
end
end
test "authenticate correctly" do
make_basic_app
simple_controller
credentials = digest_credentials(:get, "/", 'dhh', 'secret', false)
get "/", {}, 'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Digest.encode_credentials(*credentials)
assert_equal "Hello Secret", last_response.body
end
test "authenticate correctly with a param with commas" do
make_basic_app
simple_controller
uri = "/?expand=profile,address,bio"
credentials = digest_credentials(:get, uri, 'dhh', 'secret', false)
get(
uri, {},
'HTTP_AUTHORIZATION' => ActionController::HttpAuthentication::Digest.encode_credentials(*credentials)
)
# "/?expand=profile%2Caddress%2Cbio" - uri used in the server credentials
assert_equal "Hello Secret", last_response.body
end
private
def digest_credentials(method, uri, username, password, password_is_ha1)
credentials = [method.to_s.upcase, {
:uri => uri,
:realm => "SuperSecret",
:username => username,
:nonce => ActionController::HttpAuthentication::Digest.nonce(app.config.secret_token),
:opaque => ActionController::HttpAuthentication::Digest.opaque(app.config.secret_token),
}, password, password_is_ha1]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment