1

I'm creating a mobile REST API.

Currently, when user signs in with email and password, I generate secret session key (64 chars long), store it in database and send it to the user so that user doesn't need to log in again for the future request until they logged out.

For the next requests, I just check if the provided session key is equal to the one in database.

But, there is a big security loophole I see in this scheme. If the attacker got access to the database, they can use the secret key and impersonate anyone without knowing the password at all. What's the point of encrypting the password in this case besides obscuring user's real password - it doesn't prevent anything else.

So, my question is how do you store these access key correctly?

Twitter will send session key on sign in on their API. So, how do they store these keys?

Thanks.

moeseth
  • 1,855
  • 5
  • 23
  • 47

1 Answers1

0

It's even better to hash the session key, just as if it was a password, and store the hashed value in the database.

The only difference from password hashing is that, since your session keys are (I hope, at least) generated by a secure random number generator and long enough to be unguessable by brute force (I'd recommend at least 128 bits of randomness), you:

  • don't need a separate salt, and
  • can use a simple cryptographic hash function like SHA-256 instead of a deliberately slow password hashing scheme like PBKDF2.

Not using a salt also allows you to use the (hashed) session key to look up session records in the database, so you don't need a separate session ID for that.

So, to sum it up:

  1. When starting a new session, generate the session key using a secure RNG, store the SHA-256 hash of the session key in your database, and send the (unhashed) session key to the client.

  2. When the client makes a request, hash the session key sent by the client using SHA-256, and look up the corresponding record in the database.

You may also wish to limit the lifetime of session keys, and to provide some mechanism for the client to explicitly invalidate all of the user's sessions, to mitigate the effects of a compromise of individual session keys.

Community
  • 1
  • 1
Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
  • but this scheme wouldn't allow logging in the same account from multiple devices unless I have one to many relationship db table for session key. Because on the second log in, we will not know the (unhashed) session key anymore. Is that right? – moeseth Oct 24 '15 at 16:56
  • @moeseth: Right, you can't share the same session key between multiple client devices this way. Typically, one would treat these as separate *sessions* belonging to the same *user*. – Ilmari Karonen Oct 24 '15 at 17:02