Storing JWT Securely in Web Apps - Part 1

Storing JWT Securely in Web Apps - Part 1

Many of us have implemented JWT based authentication mechanism in our projects. In this post, I will share some of key points that would make sure that our implementation stays as secure as possible. Whatever I will share below will be mainly focused on using JWT as authentication token.

Authentication Vs Authorization

Authentication is about making sure that user exist on the platform.

Are you who you say you are?

Authorization is about making sure that a user has permission to access some resource.

Should you be able to do what you are trying to do?

Cookies and Session

Cookies are medium to share data between client and server, it is more like a transportation. Cookies are maintained on client, and are plain text which can't be more than 4KB in size.

Sessions are ways to make cookies data persistent on server side. Sessions can be of any type, and usually doesn't have any limit for its size.

Cookies and Sessions together can also be used as authentication mechanism.

When user is authenticated, server creates a cookie and stores the data bind to that sessionsId.

Set-Cookie: sessionId=a3fWa4342werw; Expires=Wed, 21 Oct 2021 07:28:00 GMT

Cookie-Session based authentication is very hard to manage in a distributed system.

JWT Introduction

JSON Web Token is JSON based structured token. It is a medium to share some information with guarantee of the information being genuine and not being compromised.

A JWT has three parts: header, payload and signature

Header contains information about the token itself, like type and the algorithm being used to sign the token, such as HMAC SHA256 or RSA.

Payload contains the actual information i.e. claims, such as issuer, subject, expiration time etc.

Apart from these registered claims, it can also contain some additional data like more information about the subject, for who the token is being signed, itself.

Signature is the unique hash that is generated with the help of encoded header, the encoded payload, a secret, and the algorithm specified in the header

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

image.png Key points:
• JWT is not encrypted
• JWT is just a unique hash, which is generated with header, payload and a secret. Header and Payload are always public
• JWT is more like a envelop with a guarantee that data inside isn't compromised, and can be trusted.

Possible JWT Attacks

There are other possible attacks regarding JWT, but I will mainly focus on attacks due to less secure storage.

• XSS Attack
• CSRF Attack

Thanks for reading, I will continue on how to store JWT securely and protect it against XSS and CSRF in the next part.

Did you find this article valuable?

Support Sujeet Agrahari by becoming a sponsor. Any amount is appreciated!