是否可以为 Ruby on Rails 3 中收到的每个请求“设置 Cookie”?
我希望在我的网站中随时随地加载 cookie,因为当我的 RoR 应用程序接收并接受“外部”HTTP 请求(例如:REST API)时,不会加载 cookie(请参阅 RFC2109)。所以他们的价值观是难以接近的。
仅当在我的应用程序“内部”发出 HTTP 请求时,才能访问 Cookie。
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 when the HTTP request is made "internally" in my application.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
所有浏览器都会自动发送您从域中设置的任何 cookie,您只需从任何控制器方法调用
request.cookies
即可检查它们。请求是否是从您的应用程序内部发起的(例如 302 重定向)并不重要。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.我刚刚用 Firecookie 尝试过:
cookie 由浏览器自动发送,服务器永远无法请求向其发送 cookie。
I just tried this with Firecookie:
A cookie is sent automatically by the browser, the server can never request for a cookie to be sent to it.
REST API 通常是无状态的,因此您应该避免使用服务器端会话或客户端 cookie。如果您想指示用户仅获取属于他们的资源,请使用 Rails 嵌套资源方法,这会导致如下调用:
对于属于 user001 的所有书籍。
如果您希望实现安全性,首先必须使用 HTTPS 而不是 HTTP。对于实际实现,您可以使用基本身份验证并在请求标头中设置用户名/密码,或者您可以使用 OAuth 之类的内容,它为用户在每个请求中传递的令牌设置令牌。
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:
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.