2012-09-10 76 views
3

我正在使用Ruby和Sinatra来开发应用程序。
我为了使用由齿条所提供的会话变量使用如何使机架会话cookie安全?

enable :sessions 

。我怎样才能让所有的会话cookie成为HTTPOnly?这是默认的吗?我找不到关于此的任何文档。

回答

5

而不是enable :sessions

use Rack::Session::Cookie, {:httponly => true } 

我建议使用encrypted_cookie宝石相反,它更安全。作为一个例子,这里就是我可能有一个项目:

# 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 

(解释,为什么我就躺在它这种方式 - 这种stucture的让我分裂的应用程序和使用更方便在测试中只需要app/config.rb。YMMV)

+0

非常好。我的应用程序的流程要简单得多。我可以在我的config.ru文件中使用Rack :: Builder.app语句,而不是启用:会话?另外,我通过编写set:session_secret,ENV ['SESSION_KEY'] ||来使用会话密钥“development_secret”。我可以使用机架会话cookie以相同的方式执行此操作吗? –

+0

是的,不要使用启用会话以及这个,只是生成器。你也可以执行'||'技巧,但是因为env变量会随着时间的推移而增加(因为它们非常有用),所以我把变量命令放在一个rake任务中,该任务具有设置所有env变量的先决任务具有发展价值。 – iain

+0

'Rack :: Session :: EncryptedCookie'确实提供':httponly'选项吗? –