2011-06-28 62 views
0

我想使用Ruby On Rails 2.3.8和HTTParty gem連接到API。帶有摘要式身份驗證的HTTParty

我的模型如下:

class Onnion < ActiveRecord::Base 
    require 'net/http' 
    include HTTParty 

    base_uri 'http://myapiurl.com' 
    digest_auth 'user', 'password' 
    disable_rails_query_string_format 

    def self.create_rma(order) 

    put('/orders/rma', :query => {:action => 'put', :data => {:api_key => 'user', :onnion_order_id => order.id, :customer_rma => order.saving.profile.user.id, :comments => ''}}) 
    end 
end 

我想這樣做是調用API叫做認沽的方法,具有一定的參數data參數內進行分組。

執行此方法後,我得到一個401 Unauthorized錯誤消息。

我在做什麼錯?這是我第一次嘗試做這樣的事情。

回答

0

您使用的是什麼版本的HTTParty,並且您是否嘗試過使用Github的最新版本?前段時間版本0.7.3中有一些修復與摘要授權安全性有關。

如果這不起作用,可能是您嘗試與之通話的服務器沒有正確遵循協議。我以前發生過這種情況,不得不修補HTTParty以使其正確登錄。我把我在這裏使用的補丁情況下它爲你工作...

module Net 
    module HTTPHeader 
    class DigestAuthenticator 
     # use NC = 1 instead of 0 
     def authorization_header 
     @cnonce = md5(random) 
     header = [%Q(Digest username="#{@username}"), 
      %Q(realm="#{@response['realm']}"), 
      %Q(nonce="#{@response['nonce']}"), 
      %Q(uri="#{@path}"), 
      %Q(response="#{request_digest}")] 
     [%Q(cnonce="#{@cnonce}"), 
      %Q(opaque="#{@response['opaque']}"), 
      %Q(qop="#{@response['qop']}"), 
      %Q(nc="1")].each { |field| header << field } if qop_present? 
     header 
     end 

    private 
     def request_digest 
     a = [md5(a1), @response['nonce'], md5(a2)] 
     a.insert(2, "1", @cnonce, @response['qop']) if qop_present? 
     md5(a.join(":")) 
     end 
    end 
    end 
end 

module HTTParty 
    class Request 
    def setup_digest_auth 
     # issue a get instead of a head request 
     res = http.get(uri.request_uri, options[:headers]||{}) 
     if res['www-authenticate'] != nil && res['www-authenticate'].length > 0 
     @raw_request.digest_auth(username, password, res) 
     end 
    end 
    end 
end 

所做的更改均派NC 1和NC不是0,也是這樣做的GET請求,而不是HEAD請求setup_digest_auth

+0

我使用的是0.7.8版本。所以我認爲這應該已經解決了。 –