困ったときのメモ ver.2.0

主に Ruby on Rails のメモ。など。

Rack::SSL試したいときー

2011-07-08 ちょっぴり修正

requireの順番を修正。

ごちゃまぜにして作った

ので、ソース残しとく。たぶんいろいろ間違ってるから、動くけどエラーでまくりんぐエラーも出てないっぽい。Herokuに移す前の確認用てことで。
以下のコードを「script」ディレクトリ直下に「sslrails」て名前で保存。

#!/usr/bin/env ruby.exe
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require File.expand_path('../../config/boot',  __FILE__)

require 'rubygems'
require 'rails/commands/server'
require 'rack'
require 'webrick'
require 'webrick/https'
require 'webrick/ssl'

module Rails
  class Server < ::Rack::Server
    def default_options

      # cn と comment を適当に設定
      cn = [[ "CN", WEBrick::Utils::getservername]]  
      comment = "Generated by Ruby/OpenSSL"   
      cert, rsa = WEBrick::Utils::create_self_signed_cert(1024, cn, comment)
      ssl_certificate = cert.to_s
      ssl_private_key = rsa.to_s

      super.merge({
          :Port => 443,
          :environment => (ENV['RAILS_ENV'] || "development").dup,
          :daemonize => false,
          :debugger => false,
          :pid => File.expand_path("tmp/pids/server.pid"),
          :config => File.expand_path("config.ru"),
          :SSLEnable => true,
          :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE,
          :SSLPrivateKey => OpenSSL::PKey::RSA.new(ssl_private_key),
          :SSLCertificate => OpenSSL::X509::Certificate.new(ssl_certificate),
          :SSLCertName => cn
      })
    end
  end
end

require 'rails/commands'

サーバの起動はターミナルから以下のコマンドで。

script/sslrails server

ちなみに443ポートに固定してるので注意。必要に応じて変更するべし。