我想在我的api应用程序https://github.com/seangeo/auth-hmac/
中使用这个gem我有一个关于为请求身份验证创建测试的问题。 我想用hmac签署请求,但rails controller在下一个代码
之后没有http头 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
路由有这样的配置
scope '/:token/' do
# route only json & xml format
constraints :format=> /(json|xml)/ do
resources :clients, :only => [:index]
end
end
答案 0 :(得分:3)
我在功能测试方面遇到了同样的问题。要使用AuthHMAC正确签署每个请求,您应将以下内容放在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
然后在你的功能测试中:
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
答案 1 :(得分:1)
您可以尝试此解决方案
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
由于Rails 3测试单元框架而添加的行request.env.merge!(request.env['action_dispatch.request.parameters'])
会删除action_dispatch.request
中的所有值。
您可以在此处找到此行为:https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/test_case.rb#L404