开发者

How to set cookies in ApplicationController?

I need to set cookies in my ApplicationController but I'm not sure how. I've tried using cookies - 开发者_开发百科nothing, using ActionController::Cookies - nothing. I don't need anything more then setting and getting cookies but what I do need is to set them in ApplicationController.

EDIT:

Found the answer: request.cookies['help'] = 'yes'


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 => 'example.com'
     }

     cookies.delete(:key, :domain => 'example.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"

(rails default is 20 years)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜