【问题标题】:How to make rack session cookies httponly?如何使机架会话cookie httponly?
【发布时间】:2012-09-10 00:20:20
【问题描述】:

我正在使用 Ruby 和 Sinatra 开发应用程序。
我用

enable :sessions

为了使用 rack 提供的 session 变量。如何使所有会话 cookie 都成为 HTTPOnly?默认情况下是这样的吗?我找不到这方面的任何文档。

【问题讨论】:

    标签: ruby session sinatra rack httponly


    【解决方案1】:

    而不是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)

    【讨论】:

    • 非常好。我的应用程序的流程要简单得多。我可以在我的 config.ru 文件中使用该 Rack::Builder.app 语句,而不是 enable :sessions 吗?另外,我通过编写 set :session_secret, ENV['SESSION_KEY'] || 来使用会话密钥“发展秘密”。我可以对机架会话 cookie 执行相同的操作吗?
    • 是的,不要像这个一样使用启用会话,只使用 Builder。您也可以使用|| 技巧,但是因为环境变量往往会随着时间的推移而增加(因为它们非常有用),所以我将 rackup 命令放在一个 rake 任务中,该任务具有一个先决任务,该任务设置所有环境变量发展价值。
    • Rack::Session::EncryptedCookie 真的提供:httponly 选项吗?
    • @JianWeihang 不,不是,谢谢指出。我已经更正了帖子。
    • @iain 谢谢,挖源码后发现 Encrypted::Cookie 使用了Rack::Utils.set_cookie_header!
    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2012-01-11
    • 2017-02-04
    • 2011-02-10
    • 1970-01-01
    • 2011-05-26
    • 2021-02-21
    • 2012-04-07
    相关资源
    最近更新 更多