JWT (JSON Web Token) authentication
Published: 2023-06-13 07:17:01

REST APIs are great because they are logically simple. They don’t keep complex states in memory, and they deal with resources instead of loose, unconnected functions, making their entire business logic cohesive.

However, due to the nature and mechanics underlying ‘REST APIs, securing them is not always straightforward’. What happens after the user submits their credentials? You can’t keep a state on your server side to signal when a user has logged in on their subsequent requests, so how can you know that they’ve done so correctly?

In this article, we’ll cover one very powerful yet simple way to secure a REST API using JSON Web Tokens (JWT), reviewing some best practices and implementing an example. Let’s get started!

1. What is a JWT?
2. JSON Web Token structure
3. How to use JWT to authenticate a REST API
4. Securing a secret API: Example

**What is a JWT?**
JWT stands for JSON Web Token. It is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. JWTs are commonly used for authentication and authorization purposes in web applications and APIs.

A JWT consists of three parts:

Header: Contains metadata about the type of token and the signing algorithm used. It typically includes the token type (JWT) and the signing algorithm used, such as HMAC, RSA, or ECDSA.

Payload: Contains the claims or statements about the user or entity being authenticated. Claims are represented as key-value pairs and can include standard claims (such as issuer, expiration time, subject, audience, etc.) as well as custom claims (additional information specific to your application).

Signature: The signature is created by combining the encoded header, encoded payload, and a secret key known only to the server. The signature ensures the integrity of the token and allows the server to verify its authenticity.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dlbtye2qzmpi9ef3md2h.png)

**JWT Process Diagram**

The process of using JWTs typically involves the following steps:

Authentication: Upon successful authentication, the server generates a JWT and signs it with a secret key.

Token Issuance: The server sends the JWT back to the client, usually as a response to a login request. The client then stores the JWT securely (e.g., in local storage, cookies, or other client-side storage mechanisms).

Token Usage: The client includes the JWT in subsequent requests to the server by adding it to the request headers (e.g., Authorization header) or as a query parameter.

Token Verification: On the server side, each incoming request is checked for the presence of a JWT. The server verifies the token's signature using the secret key to ensure its authenticity and integrity.

Access Control: After verifying the JWT, the server extracts the claims from the payload and performs authorization checks to determine if the user has the necessary permissions to access the requested resource.

**structure**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/feb6blc3a9jmklnlhl0y.png)


**To use JWT for authenticating a REST API, you can follow these steps:**

- Set up a JWT library: Choose a JWT library suitable for your programming language or framework. Install the library and any dependencies required.
- Generate a secret key: Create a secret key that will be used to sign and verify JWTs. This key should be kept secure and not shared publicly.
- User authentication: Implement a user authentication mechanism in your application. This could involve storing user credentials securely (such as hashed passwords) and providing a login endpoint for users to authenticate.
- Generate JWT upon successful authentication: When a user successfully logs in, generate a JWT containing the necessary claims (e.g., user ID, role, expiration time, etc.). Sign the JWT using the secret key.
- Protect API endpoints: Add authentication middleware or filters to protect your API endpoints. This middleware should validate the JWT included in the request's authorization header or query parameter.
- Verify JWT signature: On each incoming API request, extract the JWT from the request header or query parameter. Verify the JWT's signature using the secret key. If the signature is invalid, reject the request.
- Extract JWT claims: Once the JWT signature is verified, extract the claims from the JWT payload. These claims might include user ID, role, or any other relevant information.
- Implement authorization checks: Use the extracted claims to perform authorization checks and ensure that the user has the necessary permissions to access the requested resource. This could involve checking roles, scopes, or any other authorization criteria.
- Handling token expiration: If the JWT has an expiration time, handle token expiration properly. If a token has expired, return an appropriate response or provide a mechanism for users to refresh their tokens.
- Revoking tokens (optional): If you need the ability to revoke tokens (e.g., for implementing logout functionality), you can maintain a token blacklist or use token revocation mechanisms provided by some JWT libraries.

**Workflow of JWT**


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uth6wmt61zjw4i7la04q.png)

By leveraging JWTs, you can achieve stateless authentication, eliminate the need for session storage, and scale your application effectively. However, it's important to follow best practices for token handling, keep the secret key secure, and thoroughly test your implementation to ensure its security and reliability.