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

后端 未结 8 1986
不知归路
不知归路 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

    You can do this as mentioned in some of the above answers (use secure option in the config/initializers/session_store.rb file):

    MyApp::Application.config.session_store :cookie_store, key: '_my_app_session',
                                                           secure: Rails.env.production?
    

    which will only secure the session cookie, but other cookies will not be secure.

    If you want to secure all the cookies in your Rails app by default, you can use the secure_headers gem. Just add the secure_headers gem to your Gemfile, bundle install the gem and create a config/initializers/secure_headers.rb file with this content:

    SecureHeaders::Configuration.default do |config|
      config.cookies = {
        secure: true, # mark all cookies as "Secure"
      }
    end
    

    This will make all the cookies secure in your Rails app by default.

    You can also add these recommended configurations and set the httponly and samesite options as well:

    SecureHeaders::Configuration.default do |config|
      config.cookies = {
        secure: true, # mark all cookies as "Secure"
        httponly: true, # mark all cookies as "HttpOnly"
        samesite: {
          lax: true # mark all cookies as SameSite=lax
        }
      }
    end
    

提交回复
热议问题