0

我已阅读有关创建 OpenSSL 证书以及让 Webbrick 服务器运行它和 Sinatra 的教程和文档。这一切都有效 - 并且感谢之前的帖子。但是,现在我尝试将其与我的应用程序集成,我似乎丢失了解析请求并允许我从凭据中提取经过身份验证的用户名的“之前”代码。所以,我的基本问题是 - 如何同时使用 Rack::Auth::Basic 和 HTTPS,同时 WebBrick 与 Sinatra 一起运行。对此的任何帮助将不胜感激。

#!/usr/local/bin/ruby
require 'sinatra'
require 'webrick'
require 'webrick/https'
require 'openssl'

require 'yaml'

# basic authentication provided through Rack:Auth
configure do
  puts "configure do ran"
  # load password file - might move to DB at some point
  @@config = YAML.load_file(File.join(Dir.pwd, 'config', 'users.yml'))  
  use Rack::Auth::Basic, "Restricted Area" do |u, p|
    puts "use Rack::Auth::Basic"
    [u, p] == [u, @@config[:users][u][:password]]
  end
end

before do
  puts "before do ran"
  @auth ||=  Rack::Auth::Basic::Request.new(request.env)
  puts "auth username: " + @auth.username.to_s
  # set the user name for processing  in the post or get
  @myuser = @auth.username.to_s
end

class MyServer  < Sinatra::Base
  get '/' do
    # code would do something with @myuser here
    "Hello, world!"
  end       
end

pkey = cert = cert_name = nil

begin
  pkey = OpenSSL::PKey::RSA.new(File.open("private_key.pem").read)
  cert = OpenSSL::X509::Certificate.new(File.open("certificate.pem").read)
end

webrick_options = {
    :Port               => 8443,
    :Logger             => WEBrick::Log::new($stderr, WEBrick::Log::DEBUG),
    :DocumentRoot       => "/ruby/htdocs",
    :SSLEnable          => true,
    :SSLVerifyClient    => OpenSSL::SSL::VERIFY_NONE,
    :SSLCertificate     => cert,
    :SSLPrivateKey      => pkey,
    :SSLCertName        => [ [ "CN",WEBrick::Utils::getservername ] ],
    :app                  => MyServer
}

Rack::Server.start webrick_options

再次,非常感谢您对此的任何想法。

4

1 回答 1

0

如上面的评论所示,以下似乎工作正常。

class MyServer  < Sinatra::Base
  # basic authentication provided through Rack:Auth
  configure do
    puts "Configure do ran"

    # require SSL
    use Rack::SslEnforcer 
    set :session_secret, 'asdfa2342923422f1adc05c837fa234230e3594b93824b00e930ab0fb94b'

    use Rack::Session::Cookie, :key => '_rack_session',
                       :path => '/',
                       :expire_after => 2592000, # In seconds
                       :secret => session_secret

    # load password file - might move to DB at some point
    @@config = YAML.load_file(File.join(Dir.pwd, 'config', 'users.yml'))  
    use Rack::Auth::Basic, "Restricted Area" do |u, p|
      puts "use Rack::Auth::Basic"
      [u, p] == [u, @@config[:users][u][:password]]
    end
  end

  before do
    puts "Before do ran"
    @auth ||=  Rack::Auth::Basic::Request.new(request.env)
    puts "auth username: " + @auth.username.to_s
    # set the user name for processing  in the post or get
    @myuser = @auth.username.to_s
  end

  get '/' do
    # code would do something with @myuser here
    "Hello, world!"
  end
end
于 2012-11-24T10:46:42.987 回答