401 Unauthorized
Fault: Client
TL;DR
Request requires user authentication credentials.
Authentication is required and has failed or has not been provided.
What This Error Means
Authentication is required and has failed or has not been provided.
Request requires user authentication credentials.
Common Causes
- Missing Authorization header
- Invalid credentials
- Expired token
- Incorrect username/password
How to Fix It (For Visitors)
- Log in to the website
- Check your credentials
- Clear cookies and log in again
How to Fix It (For Developers/Admins)
- Include valid Authorization header
- Refresh expired tokens
- Implement OAuth flow correctly
- Check API key validity
Code Examples
Here's how to return a 401 status code in various programming languages:
Python (Flask)
from flask import Flask, jsonify
app = Flask(__name__)
@app.route('/endpoint')
def endpoint():
return jsonify({"message": "Unauthorized"}), 401
Node.js (Express)
const express = require('express');
const app = express();
app.get('/endpoint', (req, res) => {
res.status(401).json({ message: 'Unauthorized' });
});
PHP
<?php
http_response_code(401);
header('Content-Type: application/json');
echo json_encode(['message' => 'Unauthorized']);
?>
Go
package main
import (
"encoding/json"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(401)
json.NewEncoder(w).Encode(map[string]string{
"message": "Unauthorized",
})
}
Java (Spring Boot)
@GetMapping("/endpoint")
public ResponseEntity<Map<String, String>> endpoint() {
Map<String, String> response = new HashMap<>();
response.put("message", "Unauthorized");
return ResponseEntity.status(401).body(response);
}
Ruby (Sinatra)
get '/endpoint' do
status 401
json message: 'Unauthorized'
end
Browser Compatibility
| Browser | Support | Notes |
|---|---|---|
| Chrome | ✓ Full Support | All versions |
| Firefox | ✓ Full Support | All versions |
| Safari | ✓ Full Support | All versions |
| Edge | ✓ Full Support | All versions |
Official Specification
This status code is defined in RFC 7235 Section 3.1.