Shoken Startup Blog

KitchHike Founder/CTO

Facebook Graph API で OpenSSL::SSL::SSLError

RailsFacebook Graph APIを使う時に以下のようなエラーが出た場合の対応方法。

OpenSSL::SSL::SSLError

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

環境

ruby 1.9.3p194

対応方法

使用しているhttp clientのca_fileを設定する。

net/httpの場合
require 'net/http'

#OAuthに必要な各パラメータ変数をアプリごとに定義
client_id = 'xxxx'
client_secret = 'xxxx'
redirect_url = 'xxxx'

#codeはgraph apiのレスポンスから取得する
code = 'xxxx' 

https = Net::HTTP.new('graph.facebook.com', 443)
https.use_ssl = true
https.ca_file = "#{Rails.root}/config/ca-bundle.crt"
response = https.get("/oauth/access_token" +
                          "?redirect_uri=" + redirect_url +
                          "&client_id=" + client_id +
                          "&client_secret=" + client_secret +
                          "&code=" + code)
ca-bundle.crtの入手方法
[root@dev ~]# wget http://curl.haxx.se/ca/ca-bundle.crt
[root@dev ~]# cp ca-bundle.ctr {Rails.root}/config/ #{Rails.root}は環境によって変更する


参考
Ruby 1.9 and the SSL error « Martin Ottenwaelter


ところで、"net/http"と"net/https"ってどう使い分ければ良いのだろう??

追記: "net/http"と"net/https"の違い

ソース見た。
結論:マージされてるから、"net/http"使え。

ソースはここ。

ruby-1.9.3-p194/lib/net/http.rb
ruby-1.9.3-p194/lib/net/https.rb
https.rbの中身

これで全部。

=begin

= net/https -- SSL/TLS enhancement for Net::HTTP.

  This file has been merged with net/http.  There is no longer any need to
  require 'net/https' to use HTTPS.

  See Net::HTTP for details on how to make HTTPS connections.

== Info
  'OpenSSL for Ruby 2' project
  Copyright (C) 2001 GOTOU Yuuzou <gotoyuzo@notwork.org>
  All rights reserved.

== Licence
  This program is licenced under the same licence as Ruby.
  (See the file 'LICENCE'.)

=end

require 'net/http'
require 'openssl'