我正在使用 Ruby 和 Sinatra 开发应用程序。
我用
enable :sessions
为了使用 rack 提供的 session 变量。如何使所有会话 cookie 都成为 HTTPOnly?默认情况下是这样的吗?我找不到任何关于此的文档。
而不是enable :sessions
:
use Rack::Session::Cookie, {:httponly => true }
我建议改用encrypted_cookie gem,它更安全。举个例子,这是我可能会为一个项目准备的:
# app/main.rb
module Example
class App < Sinatra::Base # this class in its own file
# stuff here
end
end
# app/config.rb
require "main"
module Example
def self.app #
Rack::Builder.app do
cookie_settings = {
:key => 'usr',
:path => "/",
:expire_after => 86400, # In seconds, 1 day.
:secret => ENV["COOKIE_KEY"], # load this into the environment of the server
:httponly => true
}
cookie_settings.merge!( :secure => true ) if ENV["RACK_ENV"] == "production"
# AES encryption of cookies
use Rack::Session::EncryptedCookie, cookie_settings
# other stuff here
run App
end
end
end
# config.ru
require "app/config"
run Example.app # this in the rackup file
(为了澄清我为什么以这种方式进行布局 - 这种结构允许我将应用程序拆分并在测试中更轻松地使用它,只需要 app/config.rb.YMMV)