Authentication and Authorization in Node.js
Authentication and authorization are critical for securing your Node.js applications. Authentication verifies who the user is (like logging in with a username and password), while authorization controls what actions a user is allowed to perform (like accessing certain pages or APIs).
In Node.js, you can use libraries like Passport.js or jsonwebtoken to implement these features. For example, Passport.js offers strategies for local authentication (username/password) as well as social logins like Google and Facebook.
Once users are authenticated, you can use JSON Web Tokens (JWT) to manage sessions and protect routes. A typical flow involves generating a token upon login, then validating it on each protected route using middleware.
Here’s a basic example using JWT:
javascript
const jwt = require('jsonwebtoken');
const secret = 'mysecretkey'; // use a secure key
// Generating a token after login
const token = jwt.sign({ userId: user._id }, secret, { expiresIn: '1h' });
// Protecting a route
const authMiddleware = (req, res, next) => {
const token = req.cookies.token;
if (!token) return res.status(401).json({ message: 'Unauthorized' });
try {
const decoded = jwt.verify(token, secret);
req.userId = decoded.userId;
next();
} catch (err) {
return res.status(401).json({ message: 'Unauthorized' });
}
};
By combining authentication and authorization, you can secure your Node.js application effectively and control user access based on roles or permissions.