# 401 Unauthorized

> https://http-status.org/docs/401

**Family:** 4xx Client Error

## Rationale

Authentication credentials are missing, invalid, or expired.

## In Plain Terms

You need to prove who you are before you can access this. Please log in or provide valid credentials.

## Description

The HTTP 401 Unauthorized status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource.

## Server Perspective

### Usage
- Return 401 when credentials are absent or cannot be verified
- Use it for expired tokens when refreshing or signing in can resolve the request
- Missing authentication token or API key
- Expired authentication credentials
- Invalid login credentials
- Malformed authorization headers
- First-time access requiring authentication

### Implementation
- Include a WWW-Authenticate header with at least one authentication challenge (RFC 9110 requires this)
- Keep error details concise so credentials are not leaked

### Common Headers
- WWW-Authenticate

### Body
- Optionally include a machine-readable auth error such as token_expired

### Pitfalls
- Use 403 when the user is authenticated but still not allowed
- Avoid revealing whether a sensitive account or resource exists
- User is authenticated but lacks permission (use 403 Forbidden)
- Resource doesn't exist (use 404 Not Found)
- Request format is wrong (use 400 Bad Request)

## Client Perspective

### Pitfalls
- Do not treat 401 as a permission failure; compare it with 403

## Examples

### Missing API key

API requires authentication but no credentials provided

**Request:**
```
GET https://api.example.test/api/users
```

**Response:**
```
401 Unauthorized
WWW-Authenticate: Bearer realm="api"
Content-Type: application/json

{
  "error": "unauthorized"
}
```

### Expired JWT token

Token was valid once but has now expired

**Request:**
```
GET https://api.example.test/api/profile
Authorization: Bearer <expired-jwt>
```

**Response:**
```
401 Unauthorized
WWW-Authenticate: Bearer realm="api"
Content-Type: application/json

{
  "error": "unauthorized"
}
```

## Related Codes

- [403 Forbidden](/docs/403.md)

