Sobes.tech
Junior — Middle

What are the main advantages and disadvantages of using JSON Web Token for authentication and authorization?

sobes.tech AI

Answer from AI

Advantages of JSON Web Token (JWT):

  • Self-contained: JWT contains all the necessary information for authentication and authorization, which allows not to store state on the server.
  • Scalability: thanks to the absence of state on the server, it is easy to scale applications.
  • Convenience of transmission: JWT is a compact string that is convenient to transmit in HTTP headers or in URLs.
  • Security: JWT can be signed (for example, using HMAC or RSA), which guarantees the integrity and authenticity of the token.

Disadvantages of JWT:

  • Lack of revocation capability: after issuing a JWT, it cannot be easily revoked until it expires, unless an additional mechanism is implemented.
  • Token size: JWT can be quite large, especially if it contains a lot of data, which increases network load.
  • Storage security: if the token is stored on the client (for example, in localStorage), it can be vulnerable to XSS attacks.
  • Update complexity: updating data inside the token requires issuing a new token.

Example of using JWT in Node.js:

const jwt = require('jsonwebtoken');

// Creating a token
const token = jwt.sign({ userId: 123 }, 'secret_key', { expiresIn: '1h' });

// Verifying the token
try {
  const payload = jwt.verify(token, 'secret_key');
  console.log(payload.userId);
} catch (e) {
  console.error('Invalid or expired token');
}
What are the main advantages and disadvantages of… - sobes.tech