Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Sinatra work over HTTPS/SSL?

As the title says, Google doesn't give anything useful concerning this.

How do I set up and configure HTTPS/SSL for Sinatra apps?

How do I create a HTTPS route?

I have never used HTTPS for my apps before and have no experience tweaking Rack/whatever, so I appreciate detailed answers.

like image 370
apirogov Avatar asked Sep 12 '10 20:09

apirogov


3 Answers

this seems to do it for me:

require 'sinatra/base'
require 'webrick'
require 'webrick/https'
require 'openssl'

CERT_PATH = '/opt/myCA/server/'

webrick_options = {
        :Port               => 8443,
        :Logger             => WEBrick::Log::new($stderr, WEBrick::Log::DEBUG),
        :DocumentRoot       => "/ruby/htdocs",
        :SSLEnable          => true,
        :SSLVerifyClient    => OpenSSL::SSL::VERIFY_NONE,
        :SSLCertificate     => OpenSSL::X509::Certificate.new(  File.open(File.join(CERT_PATH, "my-server.crt")).read),
        :SSLPrivateKey      => OpenSSL::PKey::RSA.new(          File.open(File.join(CERT_PATH, "my-server.key")).read),
        :SSLCertName        => [ [ "CN",WEBrick::Utils::getservername ] ]
}

class MyServer  < Sinatra::Base
    post '/' do
      "Hellow, world!"
    end            
end

Rack::Handler::WEBrick.run MyServer, webrick_options

[hat tip to http://www.networkworld.com/columnists/2007/090507-dr-internet.html]

like image 179
richard_bw Avatar answered Nov 06 '22 10:11

richard_bw


I think using rack-ssl is the best option.

Then you just do:

class Application < Sinatra::Base
  use Rack::SSL

  get '/' do
    'SSL FTW!'
  end
end

and all http:// calls are redirected to https://

like image 16
Tomek Wałkuski Avatar answered Nov 06 '22 11:11

Tomek Wałkuski


I guess you need to setup your Web-server, not Sinatra, to work with SSL. In Sinatra you can use the request.secure? method to check for the SSL usage.

SSL + Nginx: the first article, the second one.

like image 15
Daniel O'Hara Avatar answered Nov 06 '22 11:11

Daniel O'Hara