Introduction
Authentication helps confirm who a user is. It keeps your app safe by letting only the right people in.
Jump into concepts and practice - no test required
Authentication helps confirm who a user is. It keeps your app safe by letting only the right people in.
app.post('/login', (req, res) => { const { username, password } = req.body; // Check user credentials if (username === 'user' && password === 'pass') { res.send('Login successful'); } else { res.status(401).send('Unauthorized'); } });
app.post('/login', (req, res) => { const { username, password } = req.body; if (username === 'admin' && password === '1234') { res.send('Welcome admin!'); } else { res.status(401).send('Access denied'); } });
app.get('/profile', (req, res) => { if (req.isAuthenticated()) { res.send('User profile page'); } else { res.status(401).send('Please log in'); } });
This small Express app lets users send their username and password to log in. It checks if the user exists and replies accordingly.
import express from 'express'; const app = express(); app.use(express.json()); const users = [{ username: 'user', password: 'pass' }]; app.post('/login', (req, res) => { const { username, password } = req.body; const user = users.find(u => u.username === username && u.password === password); if (user) { res.send('Login successful'); } else { res.status(401).send('Unauthorized'); } }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Never store passwords as plain text in real apps; always hash them.
Authentication is the first step to keep your app safe and private.
Authentication confirms who a user is.
It protects your app from unauthorized access.
Use it whenever you want to keep data or features private.
req.isAuthenticated() is commonly used to check if a user is logged in.app.get('/profile', (req, res) => {
if (!req.isAuthenticated()) {
res.status(401).send('Access denied');
} else {
res.send('User profile');
}
});req.isAuthenticated() is false.function auth(req, res, next) {
if (req.isAuthenticated) {
next();
} else {
res.redirect('/login');
}
}req.isAuthenticated without parentheses, treating it as a property.req.isAuthenticated().