开发者

It is possible to 'Set-Cookie's for every request received in Ruby on Rails 3?

I would like to load cookies everytime and everywhere in my website because when my RoR application receives and accepts an "external" HTTP request (ex: REST API), cookies are not loaded (see RFC2109). So their values are inaccessible.

Cookies are accessible only wh开发者_Go百科en the HTTP request is made "internally" in my application.


new_cookies = {"Cookie" => "mycookie=1234;myothercookie=4567"}
Net::HTTP.get( URI.parse( http: //app1.website.com/users ),  new_cookies)


All browsers will automatically send any cookies you set from your domain, you can check them simply by calling request.cookies from any controller method. It doesn't matter if the request was initiated from within your application (such as a 302 redirect) or not.


I just tried this with Firecookie:

  1. Created a cookie "mycoolcookie" for the domain ".stackoverflow.com"
  2. Went to stackoverflow.com, firebug showed that the cookie was sent in the request header.
  3. Went to meta.stackoverflow.com, firebug showed that the cookie was sent in the request header.
  4. Went to chat.stackoverflow.com, firebug showed that the cookie was sent in the request header.

A cookie is sent automatically by the browser, the server can never request for a cookie to be sent to it.


REST APIs are generally stateless, therefore you should avoid the use of server-side sessions or client-side cookies. If you want to indicate that a user only grabs resources belonging to them, use the Rails nested resources approach, that results in a call like:

http://abc.com/user/user001/books

For all books that belong to user001.

If you are looking to implement security, first you have to use HTTPS instead of HTTP. For the actual implementation you can use Basic Authentication and set the username/password in the request header or you can use something like OAuth which sets up a token for the user that they pass in with each request.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜