Junior — Middle
How is token verification carried out in your application?
sobes.tech AI
Answer from AI
In my application, token verification is performed using the jsonwebtoken (JWT) library. The process includes verifying the token's signature, its expiration time, and, if necessary, checking additional data (for example, the user's role).
Example of JWT verification in Node.js:
const jwt = require('jsonwebtoken');
function verifyToken(token, secret) {
try {
const decoded = jwt.verify(token, secret);
// Additional check, for example, user role
if (decoded.role !== 'admin') {
throw new Error('Insufficient rights');
}
return decoded;
} catch (err) {
// Handle verification error
console.error('Token verification error:', err.message);
return null;
}
}
// Usage
const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...';
const secret = 'your-secret-key';
const userData = verifyToken(token, secret);
if (userData) {
console.log('Token is valid:', userData);
} else {
console.log('Invalid token');
}