401

Unauthorized

4xx · Client Error common

Overview

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.

When it happens

Request / Response example

Request
GET /api/me HTTP/1.1
Host: api.example.com
Authorization: Bearer expired.token.here
Response
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token"
Content-Type: application/json

{"error":"invalid_token","message":"Access token has expired"}

In code

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>')

Common causes

How to fix

Notes

Related status codes

Related headers

Specification