Skip to content

Authentication Errors — 401 and 403 Responses

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you will learn about Authentication Errors. We cover key concepts, practical examples, and best practices to help you master this topic.

Authentication errors tell clients whether they are not authenticated (401) or authenticated but not authorized (403), with clear guidance on how to obtain proper credentials.

401 vs 403

401 Unauthorized: No authentication or invalid credentials. Include WWW-Authenticate header. 403 Forbidden: Authenticated but insufficient permissions. Explain required scope or role.

Examples

// 401 Unauthorized
{
  "status": 401,
  "error": "unauthorized",
  "message": "Authentication required. Provide a valid Bearer token.",
  "docs": "https://docs.dodatech.com/errors/unauthorized"
}

// 403 Forbidden
{
  "status": 403,
  "error": "forbidden",
  "message": "Insufficient permissions. Requires admin role.",
  "required_scope": "admin",
  "current_role": "member"
}

Implementation

// 401 handler
function requireAuth(req, res, next) {
  const token = req.headers.authorization;
  if (!token) {
    return res.status(401)
      .set("WWW-Authenticate", 'Bearer realm="dodatech"')
      .json(authError("Authentication required"));
  }
  next();
}

// 403 handler
function requireRole(role) {
  return (req, res, next) => {
    if (req.user.role !== role) {
      return res.status(403).json(forbiddenError(role, req.user.role));
    }
    next();
  };
}

Common Mistakes

  1. Returning 403 for missing auth — Use 401 when no auth is provided.
  2. No WWW-Authenticate header — 401 responses need this header.
  3. No scope information — Tell clients what permissions they need.
  4. Leaking user info — Do not reveal why authentication failed (user exists vs wrong password).

Practice Questions

  1. What is the difference between 401 and 403?
  2. What header must accompany a 401 response?
  3. What information should a 403 response include?

What's Next

In the next lesson, you will learn not-found error handling.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro