HTTP Status 401 - Unauthorized

Der HTTP-Status-Code 401 Unauthorized signalisiert, dass der Request Authentication erfordert. Client muss sich authentifizieren oder erneut authentifizieren, um Zugriff zu erhalten. Response muss WWW-Authenticate Header mit unterstützten Authentication-Schemas enthalten.

Typ

Response-Status-Code

Syntax

Der Status Code wird mit WWW-Authenticate Header zurückgegeben.

http
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="API"

Direktiven

Der 401 Unauthorized Status Code wird für Authentication-Failures verwendet.

Authentication Required
Client hat keine oder ungültige Credentials gesendet. Server fordert Authentication an bevor Request verarbeitet werden kann.
WWW-Authenticate Header
Response muss WWW-Authenticate Header enthalten mit mindestens einem Challenge (Basic, Bearer, Digest). Spezifiziert, wie Client sich authentifizieren soll.
Expired/Invalid Tokens
Für Token-basierte APIs (OAuth, JWT) signalisiert 401, dass Token expired, invalid oder revoked ist. Client muss neues Token erhalten.

Beispiele

Nachfolgend finden Sie praktische Anwendungsbeispiele für Status 401.

Beispiel 1 Missing Authentication Token

http
GET /api/users/me HTTP/1.1
Host: api.example.com

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="API", error="missing_token"
Content-Type: application/json

{"error": "authentication_required", "message": "Authorization header missing"}

Beispiel 2 Expired JWT Token

http
GET /api/protected HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGc...expired_token

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="API", error="invalid_token", error_description="Token expired"
Content-Type: application/json

{"error": "token_expired", "message": "JWT expired at 2025-10-01T10:00:00Z"}

Beispiel 3 Invalid API Key

http
GET /api/data HTTP/1.1
Host: api.example.com
X-API-Key: invalid_key_123

HTTP/1.1 401 Unauthorized
WWW-Authenticate: X-API-Key realm="API"
Content-Type: application/json

{"error": "invalid_credentials", "message": "API key not found or revoked"}

Authentication Failure Flow

401 Unauthorized Response bei fehlender oder invalider Authentication

Vorteile für die Systemarchitektur

  • Security Enforcement: Blockiert unauthenticated Requests auf Gateway-Level. Verhindert, dass unautorisierte Clients Backend-Resources erreichen.
  • Standard Authentication Flow: WWW-Authenticate Header ermöglicht Standard-compliant Authentication mit Browser-Dialogs, OAuth-Flows, oder API-Key-Handling.
  • Token Lifecycle Management: Klare Signalisierung von Expired/Invalid Tokens ermöglicht Clients, Refresh-Token-Logic zu implementieren oder Re-Authentication zu triggern.

Spezifikation

RFC 9110, Section 15.5.2 – HTTP Semantics https://www.rfc-editor.org/rfc/rfc9110.html#name-401-unauthorized

Weitere Spezifikationen

WWW-Authenticate Header, Authorization Header, HTTP Status 403 - Forbidden