Search code examples
authenticationsession

What should we store in the session when using session-based authentication?


I'm learning how to use session-based authentication for my web app, but I'm not sure what kind of data should be stored in the session.

What information do I need to keep in the session after a user logs in? Should I store things like the user's password or just their ID?


Solution

  • Firstly, you should never store passwords in plaintext; even in the DB they're stored as hashes, not as a plaintext. Technically, you could store the hashes in sessions, but there's typically no good reason to do that.

    The simplest approach is to store the userID in the session (and keep SessionID in a cookie). This way, each time the user makes a request, your server-side code can retrieve the userID from the session and use it to get any other relevant user data from the database. You can also store other data, e.g. comma-delimited permissions, in sessions, however note that in this case using JWT may be a better option.

    Also, remember that it's usually best to use the authentication methods provided by the framework you're using (ASP.NET Core, Django, etc.), rather than trying to implement your own.