Session Vs Token Authentication (PART-2)
This is a continuation from our previous post focusing on session authentication. check the article for a link to the previous article.
This article is a continuation from the previous article session vs token authentication, and in that article, session authentication was more treated and also a brief introduction to authentication in general was treated. The link to the part 1 backendharry.hashnode.dev/session-vs-token-...
Here we will be treating Token authentication using JWT and also try to make some comparisons to the two methods of authentication.
We all know tech is about solution and every tech built or made is a solution to a certain problem. But one tech isn't a universal solution as it comes with it's benefits as well as it's limitations. And session authentication is no different from that and hence births the use of Token authentication with JWTs (JSON web tokens).
How does the authentication process works?
Just like any other authentication process, the user makes a request to a server with user Data like a username and a password, the server checks against the Database and if valid, returns a 200 success response. Recall, any authentication is not complete with just this, because http is a stateless protocol so unlike the session authentication creating a session in the server memory and sending a cookie to the browser, the server creates what is called a token, and in this case a JWT (JSON web token).
The token is a randomly generated string hashed with a secret key, that holds some user information. Think of it, as a user passing data to a server and the server hashes some of the data passed to the server in order to make it difficult to read and the server as well uses a secret key to do that, so that it can have it's signature to the randomly generated string.
When the client logs in, the client is given a token by the server which the client stores anywhere convenient by it or where wanted to and then attaches or send the token back to the server for every authenticated request through the Header mostly appears as Bearer <Token Key>
.
Let us understand better more with the picture above, here the client is a browser but can be anything, can be mobile apps, even server to server as well. The main thing is a token is generated by one server and given to another which the other sends for subsequent requests. From the photo, the user logs in and the server creates a JWT with a secret information prefarably the user ID, (explanation below). For every request the token is sent through the authorization header, the token is extracted and the server checks the JWT signature which is the secret key used in hashing the data. and then if successful a 200 server response is sent to the client.
A more detailed explanation
When the client sends the token for every request, the server extracts the token from the header and when it does that, it decrypts the token to what was initially hashed which mostly at times will be any user information typically the user ID. But why hash a user information ? , its more like a rule that even after having the token being decrypted we also need to check if the user making the request is who they claim to be, so we hash an information an important one but not too important like a password (just to be safe at least if case the token gets decrypted in the wrong hands.). Say we hashed the user ID, after decrypting the token and all , we will check against the Database to see if the user with the ID exist, if it does we allow permission as authentication is complete. You can personally add other checks but this is always like the common norms at least making it too secured with steps which are stressful will just bore the user in making the app secured. Tho you might not make it directly come from the user, it could be the app/server itself doing all the checks and all that, but simplicity they say its always best.
Lets understand better with some comparisons to that of session authentication.
for session authentication the server creates a session with a session id stored on the server and sent as well to the client thus having the same session on both client and server. The Token authenticates just creates a hashed token with some user info and sends to the client. The session authentication stores session for client in a cookie, the token authentication method stores it anywhere convenient in the client. The session authentication always compares the session IDs from the cookie in client to the session Object in server memory, while the token always checks to see if the server contains the signature used in decrypting information.
comparing again, we can say the session authentication handles more work especially on the server seeing it has to as well save a session on the server which will take more space from the server or memory, hence we can say here that the JWT helps in preserving more server memory and storage space.
Also it will be difficult to scale horizontally using the session method, because we will have to save a session on a server and say we have 5 servers running for us , if we save a session on server 1, for subsequent requests it becomes probabilistic as requests can hit on server 2 or other servers whereas the session exists on server 1. Also we might want to retain user information for users to easily use the app while not logging in like a "remember me" feature , they just open the app and the app remembers their session, this is an another use case where it will be difficult to use, because logging in again might make us use another server if there are too many requests on server 1. We can use load balancers to help tho, but we will just be creating complexities for ourselves. Hence why i prefer JWT here, we just need for each server to contain the secret key, that way irrespective of the server taking the request, it will just be for it to decrypt the token with the key which we will share to all servers hence scaling horizontally becomes too possible and as well easy.
Also with session Authentication, we are sure to focus on preventing CSRF attack, as cookies which contain the user session id, can be stolen by means of embedding links to web contents which might have some malicious codes attached to those links or even a simple redirect from those links can give hackers the means to easily steal your session ID and act as you.
And again cookies don't work that too well with native apps, so when dealing with mobile app applications working with session, shows more difficult than working on the browser, the browser already comes prepared with the best working environment for cookie handling, hence session Authentication.
Those points are more like advantages to JWT and disadvantages to Session Authentication. Now, lets talk about the opposite to favor of session over JWT.
session Authentication is more secured in the server side than JWT. Obviously because, you just don't have an ID in the cookie which is stored on the client, you also have the ID on the server as well. which means you do not get to depend on just the client only but on both client and server as well.
Lets take a scenario, if we are working on a web app, which needs to be very secured on both end say a bank app, and for some reasons our users gets hacked, we can get a quick call from the real user telling us of what has happened. With this, even tho we cant get access to the ID in the client, we can simply just delete that hacked user session from the client and that client wont be able to access authenticated route, except he/she logins again to create a new session and off course we will just hope the user information are not in the hands of the hacker. So here, session Authentication has the more advantage than JWT.
if we had use a JWT method, to prevent the user from accessing routes and make requests on behalf of our user, we will need to change the secret key used in hashing the Token and doing this will not affect the hacker but will also affect all our users using the App.
Session Authentication is also very easy to use (tho if used on a small scale sever), it is easy because it has been around even till date and being popularly used, it has created new and better methods in handling security. Frameworks like Django, e.t.c come preinstalled with middlewares that prevent CSRF (Cross site request forgery) attacks, the use of CORS also helps in handling and other cool ways too.
It all boils down to which you prefer depending on your APP, do you intend on focusing on horizontally scalability and making your app diverse, or you intend on making it full time secured?, it all depends on which you prefer.
And that will be all for the topic, have a nice day and i'm hoping you had a nice read, happy hacking!.
Link to part 1 backendharry.hashnode.dev/session-vs-token-..