Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between request.cookies and cookies in a controller?

Is there a difference between request.cookies and cookies object in Ruby on Rails?

I am currently trying to send a request with a cookie from my node.js server to my ROR4 application. It seems that in the ROR application, request.cookies contains the cookie that I am sending however cookies object (on which existing logic is based) do not have it.

I have searched the docs but was not able to find anything relevant. Is there something that I have missed? Any help is appreciated.

like image 895
Vedanshu Avatar asked Jun 06 '16 12:06

Vedanshu


People also ask

What is the difference between cookie and request?

As everyone says Request. Cookies are supposed to be cookies coming from client (browser) and Response. Cookies are cookies that will be send back to client (browser).

Are cookies sent with each request?

Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web Storage API ( localStorage and sessionStorage ) and IndexedDB.


1 Answers

Ideally, request.cookies and cookies should be the same. However, in POST (create action) requests, rails verifies the XSRF token. If that verification fails, the cookies from request.cookies are not available in the request.cookie_jar. Which means, they are not available via the cookies method.

To identify if the cookies mismatch is because of the XSRF token missing. In your request, try to identify the class of your cookie hash. cookies.hash should return you ActionDispatch::Cookies::CookieJar. If it instead returns ActionController::RequestForgeryProtection::ProtectionMethods::NullSession::NullCookieJar, you have a XSRF token mismatch.

This scenario is likely to happen when you make these calls via javascript which don't by default pick the XSRF token and send with the request. See the answer here: https://stackoverflow.com/a/8175979/976880 to learn how to fix it.

like image 64
aBadAssCowboy Avatar answered Oct 06 '22 17:10

aBadAssCowboy