JSON Web Token (JWT) explained

Understand the basics of JWT and how to use them

JSON Web Token is a standard used to create access tokens for applications.

It works like this: the server generates a token that proves the user's identity and sends it to the client.

The client will send the token back to the server for each subsequent request, so the server knows that the request comes from a specific identity.

This architecture has proven to be very effective in modern web applications. In modern web applications, after authenticating the user, we will perform API requests to the REST or GraphQL API.

Who uses JWT? Take Google as an example. If you use Google API, JWT will be used.

JWT is cryptographically signed (butIs notEncryption, so HTTPS must be used when storing user data in JWT), so it can be guaranteed that we can trust it when we receive it, because no middleman can intercept and modify it or the data it saves without invalidating it .

That said, JWTs are often criticized for using them too much, especially when they are used when solutions with fewer problems are available.

You need to form your opinion around the topic. I am not advocating a technology, but to provide all available opportunities and tools.

What are they for? Mainly API authentication and server-to-server authorization.

How is the JWT token generated?

Using Node.js, you can use the following code to generate the first part of the token:

const header = { "alg": "HS256", "typ": "JWT" }
const encodedHeader = Buffer.from(JSON.stringify(header)).toString('base64')

We set the signature algorithm toHMAC SHA256(JWT supports multiple algorithms), then we create a buffer from this JSON encoding object, and then encode it with base64.

Part of the result iseyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.

Next, we add the payload, we can customize it with any type of data. There are reserved keys, includingisswithexpIdentifies the issuer and the expiration time of the token.

You can use objects to add your own data to the token:

const payload = { username: 'Flavio' }

We convert this JSON-encoded object into a Buffer, and use base64 to encode the result, as we did before:

const encodedPayload = Buffer.from(JSON.stringify(payload)).toString('base64')

In this case, part of the result iseyJ1c2VybmFtZSI6IkZsYXZpbyJ9.

Next, we obtain the signature from the header and the payload to ensure that our content will not be changed even if it is intercepted, because the signature will be invalid. For this we will usecryptoNode module:

const crypto = require('crypto')
const jwtSecret = 'secretKey'

const signature = crypto.createHmac(‘sha256’, jwtSecret).update(encodedHeader + ‘.’ + encodedPayload).digest(‘base64’)

We usesecretKeyKey and create a base64-encoded representation of the cryptographic signature.

In our case, the value of the signature is

MQWECYWUT7bayj8miVgsj8KdYI3ZRVS+WRRZjfZrGrw=

We are almost done, we just need to concatenate the header, payload and the 3 parts of the signature by separating them with a dot:

const jwt = `${encodedHeader}.${encodedPayload}.${signature}`

API authentication

This may be the only sensible way to use JWT.

The common situation is: you register for the service and download the JWT from the service dashboard. From now on, you will use this authentication to verify all requests to the server.

Instead, another use case is to send a JWT when the management API and client connect to you, and you want your users to send subsequent requests only by passing the token.

In this case, the client needs to store the token somewhere. Where is the best place? inHttpOnly cookie. Other methods are easyXSSAttacks should therefore be avoided. The HttpOnly cookie cannot be accessed from JavaScript, it is automatically sent to the origin server every time it is requested, so it is very suitable for use cases.

Choose the best JWT library

Depending on your language and environment, you can choose from many libraries. The most popular are listedjwt.iowebsite.

Don't use JWT as a session token

You should not use JWT for sessions. Use the conventional server-side session mechanism because it is more efficient and less likely to expose data.

Resources

read more

There are many documents about JWT on the Internet.

You might waste a lot of time reading blog posts and opinions. Some of these positions are