I'm implementing custom authentication & session management system in Node.js & PostgreSQL. My goal is to implement sessions that expire after 2 weeks (if not refreshed/renewed).
OWASP and other resources suggest to store unhashed session IDs both in database and cookie. However, if those session IDs are leaked from the database, then they can be used to successfully authenticate before they expire.
I wonder if hashing sessions would add some additional security against such situations. The implementation I'm thinking about would work like this:
- User authenticates.
- A session is saved to database with
id
(UUID v4) andtoken_hash
(SHA256 hash of cryptographically secure random string). - Both
id
and original unhashedtoken
are saved to response session cookie(s).
Then on subsequent requests:
- Server reads
id
andtoken
from request session cookies. - If there's a session found with
id
, then thetoken
is verified againsttoken_hash
. If it succeeds, then the user is authenticated.
(I'm thinking about using both session id
and token
/token_hash
because I think it will be faster to first find the session simply using id
, and only then verify token
against token_hash
. Otherwise, the token
would need to be hashed on every request to find the session, which, I assume, would be slower, even if some fast hashing function like BLAKE3 would be used.)