Node.js › Authentication & Authorization

What is the difference between authentication and authorization in a Node.js application?

Beginner

Answer

Authentication verifies who a user is -- confirming their identity, typically through a username/password, a token, or a third-party identity provider. Authorization determines what an already-authenticated user is allowed to do -- which resources they can access and which actions they can perform. A request must always be authenticated before it's meaningful to authorize it, but a user can be successfully authenticated and still be denied authorization for a specific action.
// Authentication: verifying identity
app.post('/login', async (req, res) => {
  const user = await verifyCredentials(req.body.username, req.body.password);
  if (!user) return res.status(401).json({ error: 'Invalid credentials' });
  req.session.userId = user.id;
});

// Authorization: checking permission for an already-authenticated user
app.delete('/posts/:id', requireAuth, (req, res) => {
  if (req.user.role !== 'admin') return res.status(403).json({ error: 'Forbidden' });
  deletePost(req.params.id);
});
Real-world example A blogging platform lets any logged-in (authenticated) user comment on posts, but only lets users with the 'editor' or 'admin' role (authorization) actually delete or edit other users' posts, checking these as two clearly separate steps in the request pipeline.

Common follow-ups: What HTTP status codes are conventionally used to distinguish an authentication failure from an authorization failure?;How does session-based authentication differ architecturally from token-based authentication?