我已阅读有关创建OpenSSL证书的教程和文档,并使用它和Sinatra运行Webbrick服务器。这一切都有效 - 并且感谢此前的帖子。但是,现在我尝试将其与我的应用程序集成,我似乎正在丢失解析请求的'before do'代码,并允许我从凭据中提取经过身份验证的用户名。所以,我的基本问题是 - 如何在与Sinatra一起运行的WebBrick的同时同时使用Rack :: Auth :: Basic和HTTPS。对此的任何帮助将不胜感激。
#!/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
同样,对此的任何想法都非常感激。
答案 0 :(得分: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