我想在Sinatra中编写一个快速的服务器应用程序。它必须是自包含的(即不使用apache / nginx / passenger),但也必须支持SSL。
是否有一种简单的方法可以为Sinatra启用SSL支持(例如使用WEBRick)?
答案 0 :(得分:9)
要使用MRI ruby执行此操作,请使用以下monkeypatch:
<强> sinatra_ssl.rb 强>:
require 'webrick/https'
module Sinatra
class Application
def self.run!
certificate_content = File.open(ssl_certificate).read
key_content = File.open(ssl_key).read
server_options = {
:Host => bind,
:Port => port,
:SSLEnable => true,
:SSLCertificate => OpenSSL::X509::Certificate.new(certificate_content),
:SSLPrivateKey => OpenSSL::PKey::RSA.new(key_content)
}
Rack::Handler::WEBrick.run self, server_options do |server|
[:INT, :TERM].each { |sig| trap(sig) { server.stop } }
server.threaded = settings.threaded if server.respond_to? :threaded=
set :running, true
end
end
end
end
然后,在您的独立应用程序中:
<强> app.rb 强>
require 'sinatra'
require 'sinatra_ssl'
set :port, 8443
set :ssl_certificate, "server.crt"
set :ssl_key, "server.key"
get "/" do
"Hello world!"
end
答案 1 :(得分:2)
使用JRuby解释器+ jetty-rackup gem(http://github.com/geekq/jetty-rackup) 在jetty-rackup gem中编辑jetty-rackup文件并添加一个SslSocketConnector,一些代码可以帮助你:
security_connector = Jetty::Security::SslSocketConnector.new
security_connector.set_acceptors(config[:acceptor_size])
security_connector.port = config[:port]
security_connector.confidential_port = config[:port]
security_connector.keystore = keystore
security_connector.password = config[:password]
security_connector.key_password = config[:key_password].nil? ? config[:password] : config[:key_password]
security_connector.truststore = truststore
security_connector.trust_password = config[:trust_pasword].nil? ? config[:password] : config[:trust_pasword]
server.add_connector(security_connector)
示例配置:
# Config
:acceptor_size: 10
:ssl: true
:keystore: keystore.jks
:password: your_pass
# :key_password: your_pass # if different
# :truststore: truststore.jks # if different
# :trust_pasword: your_pass # if different
生成keystore.jks:http://docs.codehaus.org/display/JETTY/How+to+configure+SSL