Normally i would use JWT when stateless auth is required, but i was thinking of a simple token system. Which will create a token while authenticating a user and then store that token in a SQL table with additional payloads and expiry date.

The payloads will include the user id and other informations as required.

So when i need to validate a token i would simply query in the table and check if exists and if it is expired or not.

That seems fine but i have a question here, that is if some how the database exposed to a hacker then the hacker will be able to access every users account using their token.

Now my question is, what necessary steps could be taken so that this can be prevented? Or is it a super bad idea?

  • 1
    Not super-relevant to the answer, but that is not "stateless". It's the opposite of stateless; you're storing the login state into a stateful data store (the database) and then going and querying the state of the stored data when you need to.
    – CBHacking
    May 31 '18 at 19:53
  • @CBHacking Ah .. yes!
    – rakibtg
    May 31 '18 at 19:54

The basic pattern you describe is basically the simplest way to create a stateful session management system. Your users would get an opaque session Token (a securely-random string of at least 128 bits in length), usually set in a Secure-flagged cookie. Typically you'd then have a table that stores active Sessions, with the session Token as the primary key, and foreign keys pointing to your Users table (plus any necessary metadata, such as session expiration data; don't rely on the cookie going away when it's supposed to). This is, of course, assuming you can't just store the sessions in memory (perhaps they're very long-lived, or need to be stored across servers), and has a substantial performance impact (lots of database calls) so usually you'd use a lot of caching.

If you want to use this model but prevent an attacker who successfully read your Session table from impersonating the active sessions, you can do that by running each Token through a hash function (such as SHA-256*) before storing it in the database (or looking it up in the database). That makes it still possible to quickly check for a given Token in the database, but makes it practically impossible to go from seeing the database to knowing the valid Tokens.

*It is fine to use a fast hash here (unlike for passwords), because the input string is already too high-entropy for an attacker to brute-force search for it. Similarly, you don't need a salt (although adding one won't hurt anything except some performance) because 2^128 is far too large a number for a rainbow table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.