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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With