【问题标题】:POST Requests with Ruby Faraday OpenSSL PKCS12使用 Ruby Faraday OpenSSL PKCS12 的 POST 请求
【发布时间】:2018-05-07 05:24:37
【问题描述】:

美好的一天!

我正在尝试通过带有 .p12 证书的 ssl 连接向服务器发送 POST 请求,该证书来自 Windows 7 和 Ruby 的 Faraday 库。

Ruby 的版本是 ruby​​ 2.3.3p222(2016-11-21 修订版 56859)[x64-mingw32]

Faraday gem 的版本是:faraday (0.14.0, 0.9.2)

1) 我有一个包含以下证书文件的文件夹:

  • [证书名称].crt,
  • [证书名称].csr,
  • [证书名称].key,
  • [证书名称].p12

2) 至于代码,我有以下几点:

require "faraday"
require "json"
require "openssl"
data = [JSON_object]
host = 'https://[domain_name]'
url = '[string]/[string]'
p12 = OpenSSL::PKCS12.new(File.open('[path_to_folder_with_cert_files]/[cert_name].p12', "rb").read, "[password]")
key = p12.key
cert = p12.certificate
connection = Faraday::Connection.new host, :ssl => {
  :client_cert => cert,
  :client_key => key,
  :ca_file => '[path_to_folder_with_cert_files]/[cert_name].crt',
  :verify => false
}
puts response.status = connection.post do |req|
  req.url(url)
  req.headers['Content-Type'] = @headers["content_type"]
  req.body = data
end

响应有 403 Forbidden。我已经在没有ssl连接的情况下测试了数据、url、主机参数,状态为200 OK。

请帮忙,因为我没有找到关于 Ruby 的 Faraday 和 OpenSSL::PKCS12 的这种特殊用途的教程/问题

【问题讨论】:

    标签: ruby post openssl pkcs#12 faraday


    【解决方案1】:

    以下内容对我有用:

    class Gateway
      def call
        connection.get do |req|
          req.url(url)
          req.headers['Content-Type'] = 'text/xml'
          req.body = data
        end
      end
    
      def connection
        Faraday.new(ssl: ssl) do |builder|
          builder.request :retry
          builder.response(:logger) unless Rails.env.test?
          builder.adapter :net_http
        end
      end
    
      def ssl
        {
          client_key: client_key,
          client_cert: client_cert,
          ca_file: 'CA.crt' # optional
        }
      end
    
      def url
        'https://...'
      end
    
      def client_key
        p12.key
      end
    
      def client_cert
        p12.certificate
      end
    
      def p12
        OpenSSL::PKCS12.new(p12_file.read, p12_password)
      end
    
      def p12_file
       File.open('<path-to-p12-file>', 'rb')
      end
    
      def p12_password
        'password' # if password protected
      end
    end
    

    及用法:

    puts Gateway.new.call.body
    

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 1970-01-01
      • 2012-09-16
      • 2016-06-10
      • 1970-01-01
      • 1970-01-01
      • 2014-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多