Difference between session[:food] and cookies.permanent[:food]

前端 未结 2 1881
暖寄归人
暖寄归人 2021-02-09 15:22

which are the difference between session[:food]=\"pizza\" and cookies.permanent[:food]=pizza?
I tried to read rails documentation and it says:

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-09 15:41

    I recommend you try it out, session data is base64 encoded in the cookie (rails 3) or in an encrypted cookie (rails 4) . Use a tool like Firefox 'Web Developer Extension' (WDE) addon, it has a cookie menu item, use it to delete all cookies for your localhost site, then add your code to a controller action

    session[:food] = "pizza"
    cookies.permanent[:food] = "pizza"
    

    Now view the cookies using WDE

    Name    food
    Value   pizza
    Host    localhost
    Path    /
    ...
    

    vs the session

    Name    _session_name # (this value set in config/initializers/session_store.rb)
    Value   a_base_64_value
    Host    localhost
    Path    /    
    ...
    

    now open rails console and decode the session value

    $ rails console
    > Base64.decode64('value from session')
    # works in rails 3
    

    If using rails 4 the cookie is encrypted instead of just encoded, see http://cowbell-labs.com/2013-04-10-decrypt-rails-4-session.html

    once decrypted or decoded it looks something like

    {
      "session_id"=>"xxxxx", 
      "user_return_to"=>"/", 
      "flash"=>{
        "discard"=>[:alert], 
        "flashes"=>{
          :alert=>"You need to sign in or sign up before continuing."}
        }, 
      "food"=>"pizza", 
      "_csrf_token"=>"xxxxx"
    }
    

    Note in my case I am using Devise which has added a message to the flash

    Session data is better protected and you also have the option to move to a different session store like a database without changing any code, just some configuration

提交回复
热议问题