Performance: Why authorization differs from authentication
This concept affects how quickly and securely a web app verifies user identity and grants access, impacting user interaction speed and security response.
Jump into concepts and practice - no test required
const authenticate = (req, res, next) => {
// Verify user identity once and cache
if (!req.user) {
return res.status(401).send('Not authenticated');
}
next();
};
const authorize = (role) => (req, res, next) => {
// Check user role separately
if (req.user.role !== role) {
return res.status(403).send('Not authorized');
}
next();
};
app.use(authenticate);
app.use('/admin', authorize('admin'));app.use((req, res, next) => {
// Check user role on every request without caching
if (!req.user) {
return res.status(401).send('Not authenticated');
}
if (req.user.role !== 'admin') {
return res.status(403).send('Not authorized');
}
next();
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Mixed auth checks on every request | N/A (server-side) | N/A | N/A | [X] Bad |
| Separate auth and role checks with caching | N/A (server-side) | N/A | N/A | [OK] Good |
authentication and authorization?authentication?app.get('/dashboard', (req, res) => {
if (!req.user) {
return res.status(401).send('Not authenticated');
}
if (!req.user.isAdmin) {
return res.status(403).send('Not authorized');
}
res.send('Welcome Admin');
});req.user exists; if not, sends 401 (unauthenticated).isAdmin is false, sends 403 (forbidden, unauthorized).function checkAdmin(req, res, next) {
if (!req.user.isAdmin) {
res.status(401).send('Unauthorized');
}
next();
}req.user.isAdmin without checking if req.user exists, risking a runtime error.req.user.req.user exists (authenticated), then check if role is 'editor' or 'admin'.