« Back to Index

Faraday TLS Connection

View original Gist on GitHub

Faraday TLS Connection.rb

require "faraday"
require "openssl"

class Connection
  def initialize(cert, key, host = nil)
    if cert.nil? || key.nil?
      @connection = Faraday.new host
    else
      @connection = ssl_connection(cert, key, host)
    end
  end

  def get(path)
    connection.get path
  end

  private

  attr_reader :connection

  def client_key(key)
    OpenSSL::PKey::RSA.new File.read(key)
  end

  def client_cert(cert)
    OpenSSL::X509::Certificate.new File.read(cert)
  end

  def ssl_connection(cert, key, host)
    Faraday.new(host, :ssl => ssl_options(cert, key))
  end

  def ssl_options(cert, key)
    {
      :client_cert => client_cert(cert),
      :client_key  => client_key(key),
      :verify      => false,
      :version     => "TLSv1"
    }
  end
end