【问题标题】:case sensitive headers in get request using httparty in rails使用 Rails 中的 httparty 获取请求中区分大小写的标头
【发布时间】:2018-12-21 01:35:28
【问题描述】:

我目前在使用 httparty 发出 GET 请求时遇到错误。当我使用curl 时,通话有效。错误如下:

\"验证日期\":\"1531403501\"}" }, { "error_code": "external_auth_error", "error_message": "日期标头丢失或 时间戳越界" } ] }

当我通过curl 发出请求时,这是我使用的标头。

curl -X GET -H "AuthDate: 1531403501"

但是,如您所见,请求从 AuthDate 更改为 Authdate 导致错误。这是我打电话的方式:

require 'openssl'
require 'base64'

module SeamlessGov
  class Form
    include HTTParty
    attr_accessor :form_id
    base_uri "https://nycopp.seamlessdocs.com/api"

    def initialize(id)
      @api_key = ENV['SEAMLESS_GOV_API_KEY']
      @signature = generate_signature
      @form_id = id
      @timestamp = Time.now.to_i
    end

    def relative_uri
      "/form/#{@form_id}/elements"
    end

    def create_form
      self.class.get(relative_uri, headers: generate_headers)
    end

    private

    def generate_signature
      OpenSSL::HMAC.hexdigest('sha256', ENV['SEAMLESS_GOV_SECRET'], "GET+#{relative_uri}+#{@timestamp}")
    end

    def generate_headers
      {
        "Authorization"  => "HMAC-SHA256 api_key='#{@api_key}' signature='#{@signature}'",
        "AuthDate" => @timestamp
      }
    end
  end
end

有什么解决方法吗?

【问题讨论】:

    标签: ruby ruby-on-rails-5 httparty net-http


    【解决方案1】:

    根据规范 https://stackoverflow.com/a/41169947/1518336,标头不区分大小写,因此您访问的服务器似乎有误。

    查看Net::HTTPHeader,实现了HTTParty

    与原始哈希访问不同,HTTPHeader 通过不区分大小写的键提供访问

    它看起来像 downcases 类的标题键以保持一致性。

    您可能需要查看不依赖于net/http 的其他网络库。也许curb

    【讨论】:

      【解决方案2】:

      在下面的文章中有一个解决方法

      https://github.com/jnunemaker/httparty/issues/406#issuecomment-239542015

      我创建了文件lib/net_http.rb

      require 'net/http'
      
      class Net::HTTP::ImmutableHeaderKey
        attr_reader :key
      
        def initialize(key)
          @key = key
        end
      
        def downcase
          self
        end
      
        def capitalize
          self
        end
      
        def split(*)
          [self]
        end
      
        def hash
          key.hash
        end
      
        def eql?(other)
          key.eql? other.key.eql?
        end
      
        def to_s
          def self.to_s
            key
          end
          self
        end
      end
      

      然后在标题中

      def generate_headers
            {
              "Authorization"  => "HMAC-SHA256 api_key='#{@api_key}' signature='#{@timestamp}'",
               Net::HTTP::ImmutableHeaderKey.new('AuthDate') => "#{@timestamp}"
            }
      end
      

      【讨论】:

        猜你喜欢
        • 2018-09-07
        • 2016-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-10
        • 2011-05-12
        相关资源
        最近更新 更多