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

后端 未结 8 1979
不知归路
不知归路 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条回答
  •  萌比男神i
    2021-02-01 15:04

    To force SSL and enable the secure cookie for an entire Ruby on Rails application, enable force_ssl in your environment file such as production.rb.

    # config/environments/production.rb
    config.force_ssl = true
    

    If you need to support HTTP and HTTPS traffic with your Ruby on Rails application, set the secure cookie flag for your application so that session cookies are ONLY sent over HTTPS.

    The consequence is you can no longer maintain session state over HTTP, but you at least protect yourself from session hijacking attacks.

    # config/initializers/session_store.rb
    # set secure: true, optionally only do this for certain Rails environments (e.g., Staging / Production
    Rails.application.config.session_store :cookie_store, key: '_testapp_session', secure: true
    

    Here is the video tutorial of same.

提交回复
热议问题