From the Blog

An icon for a calendar

2019-08-30

Secure Your JSON Web Token (JWT)

JSON Web Token (JWT) is a compact, URL-safe means of representing information (referred to as claims) to be transferred between client and server. The claims in a JWT are encoded as a JSON object that is used as the payload. JWT allows the server to verify and have access to the information contained in the JSON web token without storing any state on the server because of which modern-day applications are using JWT directly. JWT’s are compact and self-contained which means that token payload itself contains all the required information about the user. JSON Web Token is mainly used for:

  1. Authentication: Once the user is logged in, each subsequent request to the application includes JWT, allowing an application to have required information about the user who is making the request.
  2. Information exchange between two parties.

In their most basic form — aka JSON Web Signature (JWS) — claims are signed with a signature that can be verified by the server with a secret signing key. This ensures that the claims have not been tempered with when passed between client and server. The contents of JWS web token are Base64 encoded and not encrypted (remember encoding is different from encryption!). Base64 encoded data looks encrypted in that it looks like a garbage text but it’s actually trivially simple to turn back into readable data. Therefore it is always advised to not contain any sensitive information in JWT.

But what if you want to include any private information in a token? You don’t want your sensitive information to be present in a token that is only Base64 encoded that can be easily decoded by any attacker. Fortunately, there is a way to encrypt and guard the claims data with another, a more secure level of protection known as JSON Web Encryption (JWE). It defines a way to encrypt your claims data (which is basically JSON based data structure) so that only intended receiver can read the information present in a token. The best way to handle a web token is to:

  1. Sign it, so that it is well known that the token originated from authorized client.
  2. Encrypt it, so that only an authorized server can tell what it says.

We have a couple of good libraries that can encrypt your JSON Web Token in Java:

  1. Jose4J
  2. Nimbus-JOSE-JWT

Both the above libraries, Jose4J and Nimbus-Jose-JWT are open source (Apache 2.0) implementation of JWT and JOSE (Javascript Object Signing and Encryption) specification suite. They both are quality libraries and you can’t really make a wrong choice. However, JWT.IOhas a nice UI to show differences in each available library.

For further reading, check out: