Session cookie domain option

The host option in Endpoint config can be controlled/initialized at runtime using the endpoint init function. I don’t see a way to do the same for the session cookie domain option - that is a compile time setting for Plug.Session. Is it possible to initialize the session cookie domain option at runtime? Thanks.

1 Like

It is possible to hack this in by creating a “session cookie domain patcher” plug that does a register_before_send. Just need to make sure that this plug is the first one or included before the session plug so that it can add in the cookie domain.

It will be nice to have some official way of keeping the endpoint host and session cookie domain consistent using runtime configuration.

I had a similar problem and had a chat about it on the elixir slack. Jayjun suggested what follows:

Write a shim plug which calls Plug.Session.call(conn, Plug.Session.init(<pass runtime options here>))
It’s impossible to evaluate init/1 at runtime when using the plug SomePlug pattern.

You’d have to construct the plug per-request, but it shouldn’t be computationally expensive and it’s a relatively simple fix.

I figured I’d post it here for future alchemists :wink:

And another one from @chrismccord himself:

you could make a plug that calls the Plug.Session init, at runtime

plug MySession, ...
defmodule MySession do
  def init(opts), do: Plug.Sesson.init(opts)
  def call(conn, opts) do
    runtime_opts = Keyword.put(opts, :domain, ...)
    Plug.Session.call(conn, runtime_opts)
  end
end

in this case, I kept init at compiletime, but modified the options before calling the session plug, to do as much work as possible at compile time
but you get the idea? The plug could have just been Plug.Session.call(conn, Plug.Session.init(opts))

3 Likes

The solution above doesn’t seem to work if you have two different endpoints that should share cookies. What I ended up doing was using System.get_env and ensuring my build environment (multi-stage docker) has the proper $HOST variable set.

Sessions via document.cookie should be avoided. Use Window.sessionStorage instead…

This topic is in no way taking about javascript accessable cookies. Plug.Session by default uses http only cookies, so they’re not applicable to your concerns.

Edit:
Additionally the contents of the Plug.Session cookie are at least signed if not encrypted, so unless your secret is compromised you can be sure the cookie contains exactly what your server sent the user.

That reminds me, I need to test it to see if it poops out the ssl certificate in an error like the other web servers do… There are four ways it could be done with the others.