How can I make cookies secure (https-only) by default in rails?

后端 未结 8 1885
不知归路
不知归路 2021-02-01 14:34

In a Rails controller, I can set a cookie like this:

cookies[:foo] = \"bar\"

And specify that the \"secure\" (https-only) flag be on like this:

8条回答
  •  情深已故
    2021-02-01 15:19

    Quick and dirty solution: i think it is possible by modifying []= method in action pack cookies module (actionpack/lib/action_controller/cookies.rb)

    from:

        def []=(name, options)
          if options.is_a?(Hash)
            options = options.inject({}) { |options, pair| options[pair.first.to_s] = pair.last; options }
            options["name"] = name.to_s
          else
            options = { "name" => name.to_s, "value" => options }
          end
    
          set_cookie(options)
        end
    

    to:

        def []=(name, options)
          if options.is_a?(Hash)
            options.merge!({:secure => true})
            options = options.inject({}) { |options, pair| options[pair.first.to_s] = pair.last; options }
            options["name"] = name.to_s
          else
            options = { "name" => name.to_s, "value" => options }
          end
    
          set_cookie(options)
        end
    

提交回复
热议问题