JSON Web Tokens (JWT) are a standard for securely transmitting information between parties as a JSON object. They are commonly used for authentication in Node.js applications. This guide explains how to implement a basic JWT authentication flow.
How JWT Works
- A user logs in with their credentials.
- The server verifies the credentials and, if correct, creates a JWT and sends it back to the client.
- The client stores the JWT and includes it in the `Authorization` header for subsequent requests to protected routes.
- The server verifies the JWT on each request to a protected route before processing it.
Implementation Example
const jwt = require('jsonwebtoken');
// Login Route: Create and send a token
app.post('/login', (req, res) => {
// ...authenticate user...
const user = { id: 1, username: 'testuser' };
const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET);
res.json({ accessToken });
});
// Middleware to protect routes
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
// Protected Route
app.get('/profile', authenticateToken, (req, res) => {
res.json(req.user);
});
Comments
Post a Comment