auth-hmac functional testing problem

烂漫一生 提交于 2019-12-22 10:54:44

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/5474303/auth-hmac-functional-testing-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!