HTTP 401 Unauthorized — What It Means and How to Fix It
The HTTP 401 Unauthorized status code indicates that the client request has not been applied because it lacks valid authentication credentials for the target resource. This typically means the client tried to access a protected resource without providing any authentication, or with invalid or expired credentials.
Essential Reading: Designing Data-Intensive Applications
The system design bible for software engineers. Learn to build reliable, scalable, and maintainable systems.
Common Causes
- Missing or incorrect 'Authorization' header in the request.
- Expired authentication token (e.g., JWT, session cookie).
- Invalid username or password provided.
- Attempting to access a resource that requires authentication without logging in.
- Server-side misconfiguration of authentication mechanisms.
Code Examples to Handle HTTP 401
curl -I https://httpbin.org/status/401
How to Fix It
- Verify that an 'Authorization' header is present in your request and contains valid credentials (e.g., Bearer token, Basic Auth).
- Check the validity and expiration of your authentication token or session. If expired, obtain a new one.
- Ensure the username and password (if using Basic Auth) are correct and match the server's expected credentials.
- If using a client library or framework, confirm that it's correctly handling authentication and attaching credentials to requests.
- On the server-side, review your authentication middleware or logic to ensure it's correctly validating credentials and returning the appropriate 401 response.
Related Status Codes
Frequently Asked Questions
What causes HTTP 401?
HTTP 401 is caused by a client attempting to access a protected resource without providing valid authentication credentials. This could be due to missing credentials, incorrect username/password, or an expired authentication token.
How do I fix HTTP 401?
To fix a 401, ensure your request includes a valid 'Authorization' header with correct and unexpired credentials. If you're a developer, check your authentication logic on both the client and server sides, and ensure the server is correctly challenging the client with a 'WWW-Authenticate' header.