Why does phx_gen_auth not hash session tokens?

phx_gen_auth has two functions build_session_token and build_email_token. In build_email_token the token stored in the database is hashed while with build_session_token the token stored in the database is not hashed. Why is this? The comments in the generated code briefly mention this subject. For example, it mentions

The non-hashed token is sent to the user email while the hashed part is stored in the database. The original token cannot be reconstructed, which means anyone with read-only access to the database cannot directly use the token in the application to gain access.

Why does this concern not apply to build_session_token where it also mentions in the comments the following which I do not understand.

Generates a token that will be stored in a signed place, such as session or cookie. As they are signed, those tokens do not need to be hashed.

The goal of hashing is to avoid someone using a token they were not supposed to have access to. By hashing, we never keep the original token around, so someone looking at the database cannot steal a token to login as someone else.

Since sessions are signed, so even if someone reads a session token in the database, it is impossible for someone to use someone else’s token, unless they have access to both secret key base and signing key salt. So hashing does not add anything.

8 Likes

So would this be about a scenario such as someone getting access to the database backups but not the secrets. And the possibility of also getting access to the secrets considered not worth hashing over?

1 Like

If you loose the secret all bets are off anyways.

1 Like