📎 Webclip
Cookie Authentication with Phoenix LiveView
The post shows how Phoenix uses a signed cookie session to identify a user, starting from the default Plug.Session setup and a sample Set-Cookie header. It then traces how a server-rendered login flow stores a user id in the session and how plugs read that value to assign current_user_id and redirect unauthorized requests.
Reading notes#
- Phoenix stores the session in a signed cookie by default, so the cookie contents can be read but not changed.
- A sample response from Phoenix includes a
Set-Cookieheader that carries the session cookie. - Decoding the cookie shows that the initial request contains only a CSRF token.
- In a traditional server-rendered login flow, a successful password check calls
put_session(:user_id, id)and redirects the user. - A plug can read
get_session(conn, :user_id)and assigncurrent_user_idontoconn. - Another plug can redirect restricted requests when
current_user_idis missing. - LiveView event handlers cannot use
Plug.Conn.put_session, which creates the login problem. - The workaround stores a user id in ETS after successful login and uses a plug to copy it into
conn.assigns. - The first version of that workaround is described as not sound for production because one inserted user id would make every request appear authenticated.
- The improved version introduces a
session_uuidstored in the cookie on the first request. - The LiveView login mount receives
session_uuidfrom the session and assigns it for later use. - On login success, the LiveView handler signs the user id with
Phoenix.Tokenand stores the token in ETS under thesession_uuidkey. - A plug later looks up the token with
session_uuid, verifies it, and assignsuser_idontoconn. - The same redirect plug still blocks restricted routes when
user_idis missing. - Because
mountdoes not have access toconn.assigns, the restricted LiveView readssession_uuidfrom the session and resolves the user id through ETS and token verification. - A bonus variant also writes
user_idinto the session so restricted LiveView mounts can receive it directly. - The post ends by pointing to the GitHub commits containing the full source code.
