How to set cookies in ApplicationController? How to set cookies in ApplicationController? ruby-on-rails ruby-on-rails

How to set cookies in ApplicationController?


What do you mean by setting cookie in application controller? You would set cookie in browser corresponding to some controller action. If you want to set the cookie for all actions then you may consider using a before filter and apply that filter to all your controller actions.

You can set and delete cookies as shown below:

   cookies[:key] = {       :value => 'a yummy cookie',       :expires => 1.year.from_now,       :domain => 'domain.com'     }     cookies.delete(:key, :domain => 'domain.com')

Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie.

e.g. cookies[:user_name] = "david"


You can simplify for cookies you want to hang around for a while

cookies.permanent[:some_cookie] = "gingerbread"


Cookies are read and written through ActionController#cookies. The cookies being read are the ones received along with the request, the cookies being written will be sent out with the response. Reading a cookie does not get the cookie object itself back, just the value it holds.

cookies[:appToken] = {  value: 'IOWQ92038192319JKNJKW',  expires: 1.year.from_now,  domain: 'www.example.com',  path: '/admin',  secure: false,  httponly: false,}

path - The path for which this cookie applies. Defaults to the root of the application.

secure - Whether this cookie is only transmitted to HTTPS servers. Default is false.

httponly - Whether this cookie is accessible via scripting or only HTTP. Defaults to false. If cookie httponly is set to true, then cookie is not accessible through JavaScript. This is set for security purpose in order to protect the cookie from an attacker eavesdropping on the communication channel between the browser and the server. However, eavesdropping is not the only attack vector to grab the cookie. The attacker can take advantage of the XSS vulnerability to steal the authentication cookie. It turns out that an HttpOnly flag can be used to solve this problem.

For more information - https://api.rubyonrails.org/v5.2.1/classes/ActionDispatch/Cookies.html