JSON Web Token security concept
JSON Web Token (JWT) – A Guide to Authentication and Security

Security is a top priority for any web application, and securing APIs is equally critical. Recently, I worked on a project where we used JSON Web Token (JWT) authentication to secure APIs. This post gives a quick look at what JWT is and how it is used for authentication.

According to jwt.io, a JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. In simple words, a JWT can be thought of as a string that allows the client and server to share and authenticate data easily.

For example, when a client logs in to the application, the server verifies the user’s credentials. If authentication is successful, it generates a unique token. The server then sends this token back to the client, who uses it for future requests as proof of login.


Structure of a JSON Web Token

A JSON Web Token consists of three parts separated by dots. These three parts are:

1. Header

The header contains two elements: the type of token and the signing algorithm used. For example:

{
  "alg": "HS256",
  "typ": "JWT"
}

Here, "alg" indicates the algorithm used for encryption, and "typ" indicates the token type. HS256 shows that the token is signed using HMAC-SHA256. This structure is Base64Url encoded to form the header—the first part of the JWT.

2. Payload

The payload contains a set of claims. User-related data such as user ID or username can be stored here. In addition, JWT defines seven reserved claims commonly used in the payload.

Example:

{
  "admin": true,
  "exp": 1408621000
}

Here, "exp" is a reserved claim that defines the token’s expiration time. Like the header, the payload is Base64Url encoded to form the second part of the token.

3. Signature

The signature is the final part of the token. It is obtained by Base64Url encoding the header and payload, separating them with a dot, and then encrypting the result using the algorithm defined in the header.

Example:

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

So, a full JSON Web Token looks like this:

header.payload.signature

Using JSON Web Token for Authentication

Here’s how JWT authentication works in practice:

  1. The client logs in with credentials.
  2. The authentication server validates these credentials.
  3. If valid, it generates a token and sends it back to the client.
  4. The client stores the token locally (in local storage or cookies).
  5. For future requests to protected routes, the client includes the token in the Authorization header using the Bearer schema.

Example:

Authorization: Bearer eyGHTciu………yeG5cHI

The server then checks the Authorization header. If the token is valid, access is granted to the requested resource.

Post Comments

* marked fields are mandatory.