JWT and Session

JWT and Session

ยท

4 min read

Hello world, Today we'll discuss JsonWebToken and Sessions based Authentication; And why I prefer JWT over sessions.

Internet is stateless, whenever we try to communicate with server; It had hard time identifying between you (reader) and me (myself ๐Ÿ˜…). To make things clear, Developers introduced a system called authentication to identify their audience. Now there are many ways to implement this concept of authentication. Some prefers this and others that, But it's all right. There's no ultimate method to use so that your APIs will be secured. It's all up to you!

Two of the most used authentication concepts/methods are JWT & Sessions.

Sessions

Session based authentication has been used all over the internet and is loved by many Tech Giants. In this type of authentication, server creates a session corresponding to each user login. Session contains necessary user information and is stored somewhere in the server (in-memory, redis, mySQL etc). Session ID is sent to user as a cookie. Now each authenticated request will contain this session ID and server can identify users through their session ID by looking into stored sessions.

It's a pretty neat implementation and everything is server-side so client don't have to worry too much.

Little project

To learn about session in little depth, i would like to discuss a little project that you can also follow along.

Starting by creating github oauth as identity provider for our app.

Screenshot 2021-08-22 at 6.18.38 PM.png

Next, copy your client ID and secret and save it in server .env file

But wait where's the server and this .env file.

You can find source code for this project here:

Create a .env file on root of project with these variables:

PORT=5000
HOST=http://localhost
GITHUB_CLIENT_ID=xyzabc
GITHUB_CLIENT_SECRET=123pqr
SESSION_SECRET=ROOTZ491

Use your own github client token and secret.

Run few commands:

cd github-oauth
npm install
npm start

And we're done here, visit http://localhost:5000 and checkout the app.

It's a relatively simple application with 3 pages. Home, Login and Profile page.

User can login through github oauth page and redirects back the application. Github return logged in user's data. Now passport serialize that user data and express-session stores it in session-storage.

app.jpg

Here, once user info is stored as session, server no longer have to request github every time to get user data.

Try creating it yourself, it's fun ๐Ÿ™ƒ

Downsides

  1. Scalability issue: as session lives on server-side, default storage for session is in-memory storage which is not very good for large scale applications. But then one can always use databases for storing sessions.

    As you may have already noticed the problem here, server have to look into session storage every time user makes request, to verify the session. If session storage is a database (most probably) here, then each lookup is a read operation into database. Which can consume significant time, considering it's just verifying the user!

    In my opinion, redis is best options when it comes to session storage.
    Checkout this stack-overflow question for more.

  2. User information is not available to on client-side generally; Which can be troublesome in SPA like React apps.

JWT

JWT stands for JSON Web Token, It is used in bearer token based authentication as it bears user information. You can generate JWT with user info in it, verify it for authorization and can also use it's user information on client-side to persist state of application by decoding it.

JWT is signed with using either secret key with the HMAC algorithm or public/private key-pair using RSA algorithm.

JWT is divided into 3 parts: Header, Payload and Signature.

  • Header contains metadata about the type of token and the cryptographic algorithms used to secure its contents.

  • Payload contains identity of the user and the permissions they are allowed.

  • Signature used to validate that the token is trustworthy and has not been tampered with.

Screenshot 2021-08-22 at 10.38.24 PM.png

Here's how typical JWT looks like before and after decrypting it.
more info at https://jwt.io

Little projects

You can use JWT to secure your APIs and can also easily achieve multi-level user paradigm.

Here's source code for secure API implementation and can be accessed for testing via postman

Base URL for API: https://scratch-jwt.herokuapp.com

Screenshot 2021-08-22 at 8.01.21 PM.png

Or you can create SPA based on MERN stack followed by JWT to make things secure here ;)

app2.jpg

Share your awesome apps in comment section ๐Ÿ”ฅ

Downsides

  1. Size of JWT is much larger than that of Session IDs.

  2. Developer should not store sensitive user info in JWT as it's vulnerable to XSS.


Conclusion

Both Session and Token based authentication are good and none of them is perfect. Make sure that user input is sanitised before using it in the application to prevent XSS. Also use CSRF token in case if you're using cookies for storing your session ID (and probably you are) to prevent CSRF attacks.

References

Thank-you for reading,
C'ya

ย