Reputation: 11929
I want to use this gem in my api application https://github.com/seangeo/auth-hmac/
I have a question about creating tests for request authentification. I want to sign request with hmac but rails controller has no http headers after next code
def setup
#load from fixture
@client = clients(:client_2)
end
def sign_valid_request(request,client)
auth_hmac = AuthHMAC.new(client.key => client.secret )
auth_hmac.sign!(request,client.key)
request
end
def test_response_client_xml
@request = sign_valid_request(@request,@client)
get :index , :api_client_key => @client.key , :format=> "xml"
@xml_response = @response.body
assert_response :success
assert_select 'id' , @client.id.to_s
end
routes has such configuration
scope '/:token/' do
# route only json & xml format
constraints :format=> /(json|xml)/ do
resources :clients, :only => [:index]
end
end
Upvotes: 3
Views: 803
Reputation: 83
I had the same issue with functional testing. To correctly sign each request with AuthHMAC you should put the following in your test_helper.rb
def with_hmac_signed_requests(access_key_id, secret, &block)
unless ActionController::Base < ActionController::Testing
ActionController::Base.class_eval { include ActionController::Testing }
end
@controller.instance_eval %Q(
alias real_process_with_new_base_test process_with_new_base_test
def process_with_new_base_test(request, response)
signature = AuthHMAC.signature(request, "#{secret}")
request.env['Authorization'] = "AuthHMAC #{access_key_id}:" + signature
real_process_with_new_base_test(request, response)
end
)
yield
@controller.instance_eval %Q(
undef process_with_new_base_test
alias process_with_new_base_test real_process_with_new_base_test
)
end
then in your functional tests:
test "secret_method should be protected by an HMAC signature" do
with_hmac_signed_requests(key_id, secret) do
get :protected_method
assert_response :success
end
end
Upvotes: 3
Reputation: 2534
You can try this solution
def sign_valid_request(request,client)
auth_hmac = AuthHMAC.new(client.key => client.secret )
auth_hmac.sign!(request,client.key)
# because this would be deleted in request.recycle! method in test framework
request.env.merge!(request.env['action_dispatch.request.parameters'])
request
end
Line request.env.merge!(request.env['action_dispatch.request.parameters'])
added here because of Rails 3 test unit framework removes all values from action_dispatch.request
.
You can find this behaviour here: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/test_case.rb#L404
Upvotes: 1