Authentication with JWT
JSON Web Token (JWT) is an open standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. It's widely used for stateless authentication in APIs.
1. How it works
- User logs in with credentials.
- Server verifies credentials and creates a signed token.
- Server sends the token back to the client.
- Client sends the token in the
Authorization header for future requests. - Server verifies the signature and grants access.
2. Signing a Token
const jwt = require('jsonwebtoken');
const token = jwt.sign(
{ id: user._id, role: 'admin' },
process.env.JWT_SECRET,
{ expiresIn: '1h' }
);
3. Verifying a Token (Middleware)
You can create a middleware to protect specific routes.
const auth = (req, res, next) => {
const token = req.header('x-auth-token');
if (!token) return res.status(401).send('Access denied. No token provided.');
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (ex) {
res.status(400).send('Invalid token.');
}
};
// Usage
app.get('/api/profile', auth, (req, res) => {
res.send(req.user);
});
Security Tip: Never store sensitive information like passwords in a JWT, as the payload can be easily decoded (though not modified without the secret).