Should a cookie header be set on every response?

Let's say you're implementing sessions.

You check whether the browser presents a session cookie. If yes, you authenticate the cookie and find the user that the session is associated with, and move on processing the request.

If you didn't find a session cookie, you create a new session and send a cookie to the browser whch you expect to receive on subsequent requests.

Now my question is: if you did find a session cookie in a request, would you resend the same cookie in the response. Under what circumstances is this right?

Note: I ask this as a Pyramid (Python) programmer, because Pyramid implementation sends the session cookie unconditionally on every response. (go to code)


Generally, you don't need to set the cookie on each and every response. The browser already has the cookie and will continue sending it to the server as long as it is still valid.

Specifically, a Pyramid session cookie is set on every request because it contains a signed and timestamped secret that can expire separately from the normal cookie expiration mechanisms. By setting a new cookie each time Pyramid gets to update the embedded timestamp to show the session is still fresh. In other words, the cookie set is a different one each time.


For a session cookie (as in, a browser session cookie, that the client will destroy as soon as it is closed) I would probably not do this. It doesn't achieve anything in particular and it's a waste of bandwidth (albeit a small amount) to keep repeating yourself like this.

> Here have a cookie.
< Thanks!
> No really, have a cookie.
< Isn't that the same cookie?
> Seriously, have this cookie.
< Stop it please.

It only makes sense to send the cookie again when you are changing something about it. So for a cookie with an absolute expiry time, you may want to renew that expiry time every so often. Obviously if you are changing the value stored in the cookie, you will also send the header again.

I am generally a PHP developer, and PHP native sessions do this (send it every time unconditionally) as well. I imagine the reasons for this are a) it's easier to implement and b) it attempts to account for user agents that are not behaving as they should, possibly ignoring expiry times or failing to write cookies to client side persistent storage or <insert other odd behaviour here>.

If everyone implements 2109/2965 properly, there is absolutely no reason for setting semantically identical cookies more than once. But wouldn't a developer's life be dull if people actually read standards?

链接地址: http://www.djcxy.com/p/71946.html

上一篇: Python'请求'隐藏参数(在后)

下一篇: 是否应该在每个响应中设置Cookie标头?