401 Unauthorized
The client must authenticate itself to get the requested response.
Usually happens because:
- ☑ Missing Authorization header in request.
- ☑ Invalid or expired JSON Web
- ☑ Incorrect username or password during
🔍 Quick Checklist:
Meaning
The HTTP 401 Unauthorized client error status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.
Root Causes
- Missing Authorization header in request.
- Invalid or expired JSON Web Token (JWT) credentials.
- Incorrect username or password during Basic authentication handshakes.
| Cause | Frequency |
|---|---|
| Missing Authorization header in request. | ⭐⭐⭐⭐⭐ |
| Invalid or expired JSON Web | ⭐⭐⭐⭐ |
| Incorrect username or password during | ⭐⭐⭐ |
Common Mistakes
- Using 401 Unauthorized for users whose identity is known but lack roles (use 403 Forbidden instead).
- Omitting the WWW-Authenticate header field, which is required by HTTP standards for 401 responses.
How to Fix
Framework-Specific Examples
JSON Web Token verification returning 401 on authentication failures.
app.get('/api/secure', (req, res) => {
const authHeader = req.headers.authorization;
if (!authHeader) {
return res.status(401).set('WWW-Authenticate', 'Bearer').json({ error: 'Auth required' });
}
});Server Configuration Examples
Configuring Basic HTTP Authentication in Nginx.
location /admin {
auth_basic "Admin Area";
auth_basic_user_file /etc/nginx/.htpasswd;
}Prevention
- Establish automated middleware checking header presence early.
- Enforce short token lifetimes and implement secure refresh tokens.
Frequently Asked Questions (FAQ)
Q: What is the difference between 401 and 403?
401 Unauthorized means the user's identity is not known or verified (they are unauthenticated). 403 Forbidden means identity is known, but they do not have permission to view the resource.
Q: Why is the WWW-Authenticate header required?
It informs client applications which authentication scheme (e.g., Bearer, Basic, Digest) is expected by the server to unlock access.
Q: Does 401 trigger browser login popups?
Yes. If the server returns 'WWW-Authenticate: Basic...', the browser will display a native username/password prompt box automatically.
Q: How do clients follow a 401 response?
The client should prompt users for login, obtain credentials (e.g. a token), and re-issue the request with an 'Authorization' header.