JWT Authentication and Authorization: Best Practices for Modern Web Apps

sumit Sharmasumit Sharma
6 min read

JSON Web Token (JWT)

JWT stands for JSON Web Token. It is a compact, URL-safe means of representing claims to be transferred between two parties. It is used to securely transmit information between parties in a JSON format. JWTs can be used to authorize access to resources and services.

How Does JWT Authorization Work?

JWT authorization works by encoding information into a JSON web token (JWT), which is then passed between the client and server. The steps involved in a typical JWT authorization flow are as follows:

  • Authentication : The client sends the user’s credentials to the server, which authenticates the user and generates a JWT containing information about the user.

  • Issuing the Token: The server sends the JWT back to the client, which stores it for future use.

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

  • Verifying the Token: The server receives the request and verifies the JWT by checking its signature using the secret key that was used to sign it. If the JWT is valid, the server extracts the information contained in it and uses it to determine what actions the user is authorized to perform.

  • Authorizing the Request: If the user is authorized to access the resource, the server returns the requested data. If the user is not authorized, the server returns an error message.

API Keys vs. JWT Authorization

API keys and JWT authorization are two different mechanisms for authenticating and authorizing access to an API.

What are API keys?

An API key is a unique identifier, usually a long string of characters, used to authenticate and authorize an application or user when accessing an API. It acts like a secret password that verifies the identity of the requester, controls access, and helps track usage of the service.

What are the differences?

JWT authorization uses a JWT to represent the user’s identity and access rights. The JWT is usually generated by the authentication server after the user logs in and contains the user’s identity and access rights. The JWT is then sent with every API request as a bearer token in the authorization header.

Here is a comparison table 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, can be easily stolen.

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.

Flexibility

Limited flexibility.

More flexible, supports complex access control.

Ease of Use

Simple to use.

More complex, requires token generation and verification

General Steps for Implementing JWT Authorization in Your Application

Here are the main steps you will need to implement JWT authorization:

  • Set up a server-side application: You’ll need a backend application that will generate and verify JWTs. You can use any server-side language and framework, such as Node.js and Express.

  • Install the necessary packages: You’ll need to install a JWT library for your server-side language. For example, if you’re using Node.js, you can install the jsonwebtoken library.

  • Implement authentication: Your server-side application will need to implement authentication to verify the user’s credentials. You can use methods like email/password authentication or social media authentication.

  • Generate the JWT: Once the user has been authenticated, your server-side application will generate a JWT that contains information about the user, such as the user’s ID, name, and roles. You can sign the JWT using a secret key or a public/private key pair.

  • Send the JWT to the client: The server will send the JWT to the client, which will store it for future use.

  • Send the JWT with every request: When the client wants to access a protected resource on the server, it will send the JWT in the Authorization header of the HTTP request.

  • Verify the JWT on the server: The server will receive the request and verify the JWT by checking its signature using the secret key that was used to sign it. If the JWT is valid, the server will extract the information contained in it and use it to determine what actions the user is authorized to perform.

  • Authorize the request: If the user is authorized to access the resource, the server will return the requested data. If the user is not authorized, the server will return an error message.

Implementing JWT in a web application

1. Code to create a JSON web token

This code generates a JWT (JSON Web Token) using the jsonwebtoken library in Node.js. The token contains user data and is signed with a secret key for security.

Command to install jsonwebtoken library in NodeJS

npm install jsonwebtoken
const jwt = require('jsonwebtoken');
const secretKey = 'abcde9135';

const token = jwt.sign({
  id: 1,
  username: 'sumit'
}, secretKey, { expiresIn: '1h' });

console.log(token);

Output :

Encoded JWT

  • Importing JWT Library: The jsonwebtoken module is required to create and verify tokens.

  • Defining Secret Key: A secret key (abcde12345) is used to sign the token securely.

  • Creating JWT: The jwt.sign() method generates a token with user details (id, username) and an expiration time of 1 hour.

  • Logging the Token: The generated JWT is printed to the console for use in authentication

2. Code to verify a JSON web token.

This code verifies a JWT using the jsonwebtoken library in Node.js. It checks if the token is valid and extracts the payload if authentication succeeds.

jwt.verify(token, 'abcde12345', (err, decoded) => {
    if (err) {
      console.log('Token is invalid');
    } else {
      console.log('Decoded Token:', decoded);
    }
  });
  • Verifying the Token: The jwt.verify() method checks if the provided token is valid using the secret key.

  • Handling Errors: If verification fails, an error (err) occurs, and "Token is invalid" is logged.

  • Decoding Token Data: If valid, the decoded object contains the original user details.

  • Logging the Decoded Data: The decoded payload is printed to the console, showing user details from the token.

Advantages of using JSON Web Token

JWTs are widely used for authentication and authorization due to their numerous advantages:

  • Stateless Authentication: No need to store user sessions on the server; JWT contains all necessary data.

  • Compact & Fast: Being small in size, JWT is efficiently transmitted in HTTP headers, making it ideal for APIs.

  • Secure & Tamper-Proof: JWTs are signed using a secret key or public/private key pair, ensuring integrity.

  • Cross-Platform Support: Can be used with any technology (JavaScript, Python, Java, etc.) for authentication.

  • Built-in Expiry: Tokens can have an expiration time (expiresIn), reducing the risk of long-term access misuse.

Conclusion:

JSON Web Tokens (JWT) provide a secure, fast, and stateless way to handle authentication. They are widely used in APIs, web apps, and mobile apps due to their compact size, cross-platform support, and built-in security features. By leveraging JWT, developers can ensure safe and efficient user authentication without storing sessions on the server.

0
Subscribe to my newsletter

Read articles from sumit Sharma directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

sumit Sharma
sumit Sharma