HTTP 401 Error: Unauthorized
Authentication required: understand and resolve.
The HTTP 401 "Unauthorized" error is the standard response code indicating that authentication is required to access a resource. Despite its name, this code concerns authentication (proving identity) and not authorization (having permissions).
The 401 code is accompanied by a WWW-Authenticate header that specifies the accepted authentication mechanism (Basic, Bearer, Digest, etc.). The client can then retry with the correct credentials. This is the behavior that triggers browser login popups for sites protected by Basic Auth.
For monitoring protected APIs, 401 is a critical signal. An unexpected 401 may indicate token expiration, access revocation, or a change in authentication configuration. MoniTao allows monitoring these endpoints by configuring the appropriate authentication.
Main causes of 401 errors
The 401 error occurs when authentication fails. Here are the most common causes:
- Missing credentials: The request doesn't contain an Authorization header while the resource requires it. This is the simplest case.
- Expired token: JWTs and OAuth tokens have a limited lifetime. Past this period, they are rejected with a 401.
- Revoked token: A token can be invalidated server-side (logout, password change, manual revocation) while remaining valid client-side.
- Incorrect credentials: Wrong login/password, miscoded API key, or secret modified without client-side update.
Difference between 401 and 403
These two codes are often confused but have distinct meanings:
- 401 Unauthorized: "Who are you?" - Identity is not established. The client must provide valid credentials.
- 403 Forbidden: "You don't have permission" - Identity is known but permissions are insufficient.
- Appropriate action: 401 = request authentication. 403 = no point retrying with the same credentials.
- Correct semantics: Use 401 for unauthenticated endpoints, 403 for authenticated but unauthorized access.
Resolving 401 errors
Based on the identified cause, here are the solutions to apply:
- Check credentials: Ensure the token or credentials are correct. Watch for leading/trailing spaces and case sensitivity.
- Renew the token: If the token is expired, use the refresh token or regenerate a new one through the provided mechanism.
- Check format: The Authorization header must have the correct format: "Bearer
" or "Basic ". - Check logs: Server logs may indicate the exact reason for rejection: malformed token, invalid signature, etc.
HTTP authentication examples
Here's how to configure authentication for different types of requests:
# cURL - Basic Auth
curl -u username:password https://api.example.com/resource
# cURL - Bearer Token
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..." https://api.example.com/resource
# JavaScript fetch - Bearer Token
fetch("https://api.example.com/resource", {
headers: {
"Authorization": "Bearer " + accessToken
}
})
# PHP - Server-side verification
$authHeader = $_SERVER["HTTP_AUTHORIZATION"] ?? "";
if (!preg_match("/Bearer\s+(\S+)/", $authHeader, $matches)) {
http_response_code(401);
header("WWW-Authenticate: Bearer");
exit(json_encode(["error" => "Token required"]));
}
The WWW-Authenticate header in the 401 response tells the client which authentication mechanism to use.
Monitoring authenticated endpoints
Monitoring protected APIs requires specific configuration:
- Configure authentication: In MoniTao, add your credentials (Basic Auth or Bearer Token) in the monitor configuration.
- Monitor expiration: Configure alerts to be notified before monitoring tokens expire.
- Dedicated account: Create a specific account or token for monitoring with minimal permissions (read-only).
- Planned rotation: Schedule monitoring token rotation before expiration to avoid false alerts.
Authentication checklist
- Authorization header present and properly formatted
- Valid and non-expired token/credentials
- Monitoring account with minimal permissions created
- Long-lived monitoring token configured
- Rotation procedure documented and scheduled
- Alert configured for unexpected 401
Frequently asked questions about HTTP 401
Why is 401 called "Unauthorized" when it's about authentication?
It's a historical misnomer in the HTTP specification. The correct term would be "Unauthenticated". RFC 7235 maintains this name for backward compatibility.
How to monitor an API with JWT authentication?
Configure a MoniTao monitor with an Authorization: Bearer
My monitor receives 401 even though the token is valid. Why?
Check: 1) Exact header format (Bearer with capital B, single space). 2) No invisible spaces around the token. 3) Token not revoked server-side.
How to avoid false 401 alerts due to token expiration?
Use long-lived tokens for monitoring, or implement automatic rotation with alerts N days before expiration.
What if my API returns 401 instead of 403 for unauthorized access?
This is a server-side implementation error. 401 should only be used when identity is not established. For an authenticated user without permissions, it's 403.
How to handle automatic token renewal?
Implement a refresh token system. When the access token expires (401), use the refresh token to get a new one without re-requesting credentials.
Conclusion
The HTTP 401 Unauthorized error signals an authentication problem: missing, expired, or invalid credentials. Understanding the difference with 403 (authorization) enables implementing more robust security systems.
MoniTao supports monitoring protected APIs with Basic Auth and Bearer Token. Configure your monitors with dedicated long-lived tokens and receive alerts for unexpected 401s, signaling an authentication problem to resolve immediately.
Useful Links
Ready to Sleep Soundly?
Start free, no credit card required.