Session Authentication vs Token Authentication

Authentication helps verifying the identity of a user. There are many ways we can provide authentication to check our internet resources (Websites, APIs). In this post I am going to tell you the two mainly used authentication types.

  • Session Based Authentication
  • Token Based Authentication

Session Based Authentication

In today’s internet world many web sites are session based and easy to implement. Mostly all frameworks gives support for Session based authentication. In this type of Authentication, server side code will validate given user details and authentication data. Once it was passed, it will create session variable in server memory or database or somewhere in server side. It stores required data in it like logged User Id and User Name etc.. And it will create a session id for this object and send it to client/browser in response cookie. Client/browser will cache the cookie and store it in local memory. From now whenever sending subsequent request to server it will send this cookie data to server, until cookie expired.

Set Session variables
SESSION["user_id"] = "123";
SESSION["user_name"] = "Harish";

Get Session variables
if (isset(SESSION['user_id']))
{
//Do stuff
}

Session is stored in server, means it will increase load on server. Bad scale-ability (especially over more than one server farm).

Token based Authentication

This is almost similar update validating user details in server side and create an encrypted token and send it back to client/browser in response cookie.

Here server will not store any information about current user. From next subsequent requests it will be authenticated using that encrypted token. This encrypted token will be carried to server in cookie or in request header. In server side code it will be decrypted using secret key only server will know that. We can implement this kind of authentication using HMAC, AES, RSA type of encrptions.

HMAC-SHA1
var token = User_id|expiry_date|HMAC(User_id|expiry_date, secret_key) //This secret_key only server knows about it
Here User_id and expiry_date are sent in plaintext with the resulting encrypted hash text attached. Plain text user id and expiry date will help to compare text again with encrypted text to validate. Because SHA1 algorithm is one way encryption only.

AES
var token = AES.encrypt(user_id|expiry_date, secret_key)
In this case will only send encrypted token to client/browser and it will send in subsequent requests. In server side code will decrypt the token with same secret key.
var data = AES.decrypt(token_text, secret_key)

RSA will have public and private key to encrypt and decrypt data.

There are many free libs for authentication management. Select the best one which suit your business.