Which of the following best explains why authentication is crucial in Express applications?
Think about what happens if anyone can access all parts of the app.
Authentication helps verify user identity so only allowed users can see or change sensitive information.
Given an Express route protected by authentication middleware, what is the typical behavior when an unauthenticated user tries to access it?
app.get('/dashboard', authMiddleware, (req, res) => { res.send('Welcome!'); });
Think about what the middleware does if it doesn't find a logged-in user.
Authentication middleware blocks access and usually redirects or sends an error if the user is not logged in.
Consider this Express middleware that checks for a token in headers. What will the server respond if the token is missing?
function authMiddleware(req, res, next) {
if (!req.headers['authorization']) {
return res.status(401).send('Access denied');
}
next();
}
app.get('/profile', authMiddleware, (req, res) => {
res.send('User profile');
});Look at the condition checking the authorization header.
If the authorization header is missing, the middleware sends a 401 status and stops further processing.
Which option contains the correct syntax for an Express middleware that checks if a user is authenticated?
function auth(req, res, next) {
if (req.user) {
next();
} else {
res.status(401).send('Unauthorized');
}
}Check for missing parentheses and semicolons.
Option A uses correct if statement syntax with parentheses and braces. Options A, C, and D have syntax errors or missing semicolons.
Review this middleware code. Why does it allow unauthenticated users to access protected routes?
function authMiddleware(req, res, next) {
if (req.user === undefined) {
next();
} else {
res.status(401).send('Unauthorized');
}
}Check the logic of the if condition and what happens when req.user is missing.
The middleware incorrectly calls next() when req.user is undefined, so unauthenticated users proceed. The logic should be reversed.