What is HTTP Response Status Code 401 Unauthorized?
HTTP response status code 401 Unauthorized indicates that the client must authenticate itself to get the requested resource. The server requires valid credentials.
When is HTTP Response Status Code 401 Unauthorized Used?
The 401 status code is used when a client attempts to access a protected resource without proper authentication or with invalid credentials.
Example 1: Missing Authentication Header
# Client sends a request without authentication. GET /api/secure-data HTTP/1.1 Host: api.example.com # Server Response HTTP/1.1 401 Unauthorized Date: Wed, 09 Oct 2024 14:10:00 GMT Server: Apache/2.4.41 (Ubuntu) WWW-Authenticate: Bearer realm="example" # The server requests authentication for accessing the resource.
Example 2: Invalid Token
# Client sends a request with an invalid token. GET /api/secure-data HTTP/1.1 Host: api.example.com Authorization: Bearer invalid_token # Server Response HTTP/1.1 401 Unauthorized Date: Wed, 09 Oct 2024 14:12:00 GMT Server: Nginx/1.18.0 WWW-Authenticate: Bearer realm="example" # The server informs the client that the provided token is invalid.
Summary
The HTTP 401 Unauthorized status code is used when a client must provide valid credentials to access a resource. It prompts the client to authenticate and try the request again.