0

我想使用 Ruby On Rails 2.3.8 和 HTTParty gem 连接到 API。

我的模型如下:

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

我想做的是调用一个名为 Put 的 API 方法,其中某些参数分组在dataparameter.xml 中。

执行此方法后,我收到一条401 Unauthorized错误消息。

我究竟做错了什么?这是我第一次尝试做这样的事情。

4

1 回答 1

0

您使用的是什么版本的 HTTParty,您是否尝试过使用来自 Github 的最新版本?不久前在 version 中有一些与摘要身份验证安全性有关的修复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

于 2011-06-28T15:52:06.510 回答