Why does the session cookie work when serving from a domain but not when using an IP?

This is a “bug” in Chrome, not a problem with your application. (It may also affect other browsers as well if they change their policies.)

RFC 2109, which describes how cookies are handled, seems to indicate that cookie domains must be an FQDN with a TLD (.com, .net, etc.) or be an exact match IP address. The original Netscape cookie spec does not mention IP addresses at all.

The Chrome developers have decided to be more strict than other browsers about what values they accept for cookie domains. While at one point they corrected a bug that prevented cookies on IP addresses, they have apparently backpedaled since then and don’t allow cookies on non-FQDN domains (including localhost) or IP addresses. They have stated they will not fix this, as they do not consider it a bug.

The reason “normal” cookies are working but the session cookie is not is that you are not setting a domain for the “normal” cookies (it’s an optional parameter), but Flask automatically sets the domain for the session cookie to the SERVER_NAME. Chrome (and others) accept cookies without domains and auto-set them to the domain of the response, hence the observed difference in behavior. You can observer normal cookies failing if you set the domain to the IP address.

During development, you can get around this by running the app on localhost rather than letting it default to 127.0.0.1. Flask has a workaround that won’t send the domain for the session cookie if the server name is localhost. app.run('localhost')

In production, there aren’t any real solutions. You could serve this on a domain rather than an IP, which would solve it but might not be possible in your environment. You could mandate that all your clients use something besides Chrome, which isn’t practical. Or you could provide a different session interface to Flask that does the same workaround for IPs that it already uses for localhost, although this is probably insecure in some way.

Chrome does not allow cookies with IPs for the domain, and there is no practical workaround.

Leave a Comment