DEV Community

Cover image for Ultimate Guite to JSON Web Token(JWT) Authorization
Bhavesh Yadav
Bhavesh Yadav

Posted on

Ultimate Guite to JSON Web Token(JWT) Authorization

Hey folks, Today we'll be seeing a very interesting topic i.e. JSON Web Token aka JWT.

JSON Web Token (JWT) is a widely adopted standard for secure user authentication and authorization. It plays a vital role in securely transmitting data between parties. In this comprehensive guide, we will explore the fundamentals of JWT authorization, its best use cases, and effective implementation practices for your use case.


What is JWT Authorization?

JWT stands for JSON Web Token, which serves as a compact and URL-safe representation of claims exchanged between parties. It is mainly used to authorize access to resources and services, JWT authorization provides a stateless mechanism that eliminates the need for sessions.

By digitally signing JWTs with a secret key known only to the server, the data integrity is ensured during transmission, protecting it from unauthorized tampering.


How Does JWT Authorization Work?

JWT authorization operates by encoding information into a JSON web token (JWT), basically a computed string and transferring it between the client and server.

Note: Never ever store sensitive info inside JWT because anyone can see the details inside the JWT, for example: For making a JWT you have to give something called payload, which can be anything related to user like its id or email or both. Using this payload and secret key(which only server has) JWT are created and issued. Anyone can see the details inside JWT but no one can change it without the correct secret key. So if your secret key is compromised then sorry my friend you're in big trouble.

The typical flow of JWT authorization involves the following steps:

  1. Authentication: The client sends the user's login credentials to the server, which authenticates the user and generates a JWT containing relevant user information.

  2. Token Issuance: The server sends the JWT back to the client, who stores it for future use.

  3. Sending the Token: When the client wants to access a protected resource on the server, it includes the JWT in the Authorization header of the HTTP request.

  4. Token Verification: The server receives the request and verifies the supplied JWT by checking its signature using the secret key. If the JWT is valid, the server extracts the information to determine the user's authorized actions.

  5. Request Authorization: If the user is authorized to access the requested resource, the server returns the corresponding data; otherwise, an error message is returned.

JWT authorization ensures secure and efficient communication between the client and server, as it eliminates the need for the server to store session information. This makes it an ideal choice for decentralized systems like microservice architectures, where multiple independent components require secure communication.


JWT Authorization vs. API Keys

API keys and JWT authorization are distinct mechanisms for authenticating and authorizing API access.

API Keys

API keys generally consist of long strings of characters shared between API providers and clients. Typically sent as parameters or headers in API requests, API keys primarily identify the client and can limit API usage.

JWT Authorization

In contrast, JWT authorization employs JWTs to represent a user's identity and access rights. After a successful user login, the authentication server generates a JWT encapsulating the user's relevant information. For subsequent API requests, the client includes this JWT as a bearer token in the authorization header.

Here's a comparison table outlining the key differences between API keys and JWT authorization:

Feature API Keys JWT Authorization
Purpose Identifies the client, limits API usage Authenticates and authorizes the user
Format Long string of characters Encoded JSON object
Security Less secure, prone to theft More secure, digitally signed and encrypted
Usage Sent as a parameter or header with each request Sent as a bearer token in the authorization header
Authentication Not used for authentication Used for authentication
Authorization Not used for authorization Used for authorization
Flexibility Limited flexibility More flexible, supports complex access control
Ease of Use Simple to use More complex, requires token generation and verification
Standardization Not standardized, varies by API provider Standardized, based on JWT standard

In summary, while API keys offer simplicity, they are less secure and flexible compared to JWT authorization. If you prioritize security and a versatile authentication and authorization mechanism, JWT authorization is the way to go.


General Steps for Implementing JWT Authorization in Your Application

To implement JWT authorization in your application, follow these primary steps:

  1. Set up a server-side application: Create a backend application using a suitable server-side language or framework (e.g., Node.js with Express or my favourite Nestjs) capable of generating and verifying JWTs.

  2. Install the necessary packages: Install a JWT library specific to your chosen server-side language. For instance, if you're using Node.js, you can install the popular jsonwebtoken library.

  3. Implement authentication: Develop the necessary authentication methods in your server-side application to verify user credentials. This can involve techniques like email/password authentication or social media authentication.

  4. Generate the JWT: After successful authentication, your server-side application should generate a JWT containing relevant user information, such as the user's ID, name, and roles. Ensure that you sign the JWT using a secret key which should always be a env variable to be more secure.

  5. Send the JWT to the client: Transmit the generated JWT from the server to the client, who will store it for future use.

  6. Send the JWT with every request: To access protected resources on the server, the client should include the JWT in the Authorization header of each relevant HTTP request.

  7. Verify the JWT on the server: Upon receiving the request, the server verifies the JWT by checking its signature using the corresponding secret key. If the JWT is valid, the server extracts the contained information to determine the user's authorized actions.

  8. Authorize the request: If the user possesses the necessary authorization to access the requested resource, the server responds with the requested data; otherwise, an error message is returned.

By diligently following these steps, you can successfully implement JWT authorization in your application and ensure secure communication between the client and server.


Conclusion

In conclusion, embrace the power of JWT authorization and enhance the security and flexibility of your API access. Follow the specified steps and Secure communication and streamlined access control are just a few steps away!


Top comments (2)

Collapse
 
priyansh121096 profile image
Priyansh Agrawal

What happens when a JWT is compromised? Since it's exchange happens in an open channel (browser).

Collapse
 
codezera profile image
Bhavesh Yadav

Yeah so basically if someone has your JWT token then he/she will be able to request to the server on behalf of you, but JWT's have a expired time so if your JWT token is compromised then the person who has it can use it just for some time ant it will expire in some time whatever is set by the server.

Main issue comes when your JWT secret is compromised, because when you create a jwt then you sign it with a secret and if that secret is compromised then you're in big trouble because the JWT authorization works is you give jwt token to a server first server decodes it (any one can do it go to jwt.io and scroll down you'll see a example) then server takes the payload and verifies it by making another token with that payload and the secret which server has if the token generated by server and token given by client is same then token is verified(ignore the case of expiry date for now).

This is how JWT basically works behind the hood