The principle of sessions is to save data on server side that can be accessed only by the user that has the corresponding session id.
There are two kinds of data: private or public in relationship with the client. Session it’s private for public access of course.
We usually store an user id and some random data(i don’t have any concrete example).
I am thinking about not using sessions at all. Instead using a function that checks for the validity of the data sent by user. The server would have a private key that will use for hashing user data.
For example if an user has an id = 9999 we usually store it in a file associated with the session id. Every time the client is making a request we check its session id and retrieve data from the session file associated with it.
I am thinking of storing session data on client side, and every time the client makes a request it sends the hash of this data and the data.
If the user logs in it sends its credentials and the server returns its id a timestamp and a hash calculated based on the user id and the private key.
For any future request the server uses the same function and if the resulting hash is the same then the session is valid and data is previously verified.
Is this a valid way of replacing sessions?
What drawbacks there are beside not being to save server-private session data?
I was concerned by speed and I made a small test…
<?php
$session = array(
'userId' => 999,
'timestamp' => time()
);
$privateKey = 'da39a3ee5e6b4b0d3255bfef95601890afd80709';
$startTime = microtime(true);
for ($i = 0; $i < 1000000; $i++){
$hash = hash_hmac('sha1', json_encode($session), $privateKey);
}
echo 'Script took ' . (microtime(true) - $startTime) . ' seconds';
…that prints
Script took 5.246542930603 seconds
I ran this on a laptop(Intel Duo).
In my opinion this is an affordable time(0.000005247 per hash).
Is the test correct?
EDIT: a timestamp is hashed along with the user id in order to ensure session expiration. So that on server side even if the session is valid but it is too old it can be considered as expired.
So to if we are hashing the data along with a timestamp using a private key is it usable in production?
I can think of a few drawbacks…
or space this saves you.