Junior — Middle
Have you provided a solution for implementing authentication and authorization systems in Node.js applications?
sobes.tech AI
Answer from AI
Yes, the following approaches are often used to implement authentication and authorization systems in Node.js:
-
Authentication using JWT (JSON Web Tokens): the user enters a login and password, the server verifies them, and upon successful authentication, issues a token that the client sends in headers to access protected resources.
-
Using middleware, such as Passport.js, which supports many authentication strategies (local, OAuth, JWT, etc.).
-
Authorization is implemented through checking user roles or permissions, which are stored in the database or in the token.
Example of a simple JWT authentication:
const express = require('express');
const jwt = require('jsonwebtoken');
const app = express();
app.use(express.json());
const users = [{ id: 1, username: 'user', password: 'pass', role: 'admin' }];
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);
if (!user) return res.status(401).send('Invalid credentials');
const token = jwt.sign({ id: user.id, role: user.role }, 'secretKey', { expiresIn: '1h' });
res.json({ token });
});
function authMiddleware(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader) return res.status(401).send('No token');
const token = authHeader.split(' ')[1];
jwt.verify(token, 'secretKey', (err, user) => {
if (err) return res.status(403).send('Invalid token');
req.user = user;
next();
});
}
app.get('/protected', authMiddleware, (req, res) => {
if (req.user.role !== 'admin') return res.status(403).send('Forbidden');
res.send('Protected data');
});
app.listen(3000);
This approach provides basic protection and access control in Node.js applications.