401 Unauthorized means authentication is required and the request was rejected because credentials are missing or invalid. Despite the name "Unauthorized," it really means "unauthenticated" — the server could not verify who is making the request.
By spec a 401 response should include a WWW-Authenticate header stating which auth scheme to use. It implies access may be possible after re-authenticating with valid credentials, which distinguishes it from 403 where re-authenticating will not help.
GET /api/me HTTP/1.1
Host: api.example.com
Authorization: Bearer expired.token.hereHTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token"
Content-Type: application/json
{"error":"invalid_token","message":"Access token has expired"}app.use('/api', (req, res, next) => {
const token = req.headers.authorization;
if (!isValid(token))
return res.status(401).set('WWW-Authenticate', 'Bearer').json({ error: 'invalid_token' });
next();
});curl -i https://api.example.com/api/me
# -> 401 Unauthorized (add: -H 'Authorization: Bearer <token>')