Why does `phx_gen_auth` create a session token? (and other questions)

Hello :wave:

I have a few questions about the authentication system generator for Phoenix.

  1. Does the generated code cover authentication for SPA clients? Which part would need to be adapted?

  2. Why is there a session token generated in the user codebase?
    When using Plug.Conn.put_session/3, Phoenix already generates a cookie-session (it uses Phoenix.Token if I’m not wrong), where one can for example store the user ID. The cookie is signed and cannot be altered. The subsequent requests can retrieve the user ID from the cookie and user data can be fetched from db.
    However, instead of storing just the user ID in the Phoenix token with put_session/3, the generator stores a token in the Phoenix token itself (and then retrieves user data from db based on the token). Isn’t that redundant? Why do we need to create a session token in the user codebase if put_session/3/get_session/2 handles that already?

I’ll start with these two questions first:) Thank you for any help.

Only with a session token in the db you can invalidate a single compromised session. For stateless session management a compromised session would mean you need to either change your signing secret β€” and therefore invalidate all your active sessions β€” or wait for the compromised session to timeout potentially doing more damage in the meantime.

You could remove access at other level, e.g. deactivate the account for the compromised session, but this would lock the account even for legitimate usage on other sessions.