Junior — Middle
Do you have experience working with JSON Web Token for authentication and authorization?
sobes.tech AI
Answer from AI
JSON Web Token (JWT) is a compact, URL-safe way to transmit information between parties as a JSON object. In Node.js, JWT is often used for user authentication and authorization.
The main idea: after a user successfully logs in, the server creates a JWT containing a payload (e.g., user ID and role), signs it with a secret key, and sends it to the client. The client then includes this token in the Authorization header for subsequent requests. The server verifies the token's signature and extracts data to confirm access rights.
Example of creating and verifying JWT using the jsonwebtoken library:
const jwt = require('jsonwebtoken');
const secret = 'your-secret-key';
// Creating a token
const token = jwt.sign({ userId: 123, role: 'admin' }, secret, { expiresIn: '1h' });
// Verifying the token
try {
const decoded = jwt.verify(token, secret);
console.log(decoded.userId); // 123
} catch (err) {
console.error('Invalid token');
}
Thus, JWT allows secure transmission of user information and rights without the need to store sessions on the server.