401 Unauthorized

When a client makes a HTTP request, but the server requires the request to be authenticated a 401 Unauthorized status is returned.

This could mean that a user needs to log in first, or more generally that authentication credentials are required. It could also mean that the provided credentials were incorrect.

The name Unauthorized can be a bit confusing, and was regarded as a bit of misnomer. 401 is strictly used for Authentication. In cases where you want to indicate to a client that they simply aren’t allowed to do something, you need 403 Forbidden instead.

When a server sends back 401, it must also send back a WWW-Authenticate header. This header tells a client what kind of authentication scheme the server expects.

Examples

This is an example of a server that wants the client to login using Basic authentication.

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic; realm="Secured area"

This is an example using Digest auth:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Digest realm="http-auth@example.org", qop="auth, auth-int",
    algorithm=SHA-256, nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v",
    opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS

OAuth2 uses something called Bearer tokens, which is really just a secret string:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer

It’s possible for a server to tell a client it supports more than one scheme. This example might be from an API that normally uses OAuth2, but also allows Basic for developing/debugging purposes.

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic; realm="Dev zone", Bearer

Due to how HTTP works, the above header is identical to the following:

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic; realm="Dev zone"
WWW-Authenticate: Bearer

If a client got the correct credentials, it generally sends them to servers using the Authorization header:

GET / HTTP/1.1
Authorization: Basic d2VsbCBkb25lOnlvdSBmb3VuZCB0aGUgZWFzdGVyIGVnZwo=

Other authentication schemes

IANA has a list of standard authentication schemes. Aside from Bearer, Digest and Bearer there is also:

  • HOBA
  • Mutual
  • Negotiate
  • OAuth (v1)
  • SCRAM-SHA-1
  • SCRAM-SHA-256
  • vapid

Most of those are less common, some should probably no longer be used. There’s also various auth schemes defined by others in the community:

  • Hawk, made by a disillusioned former OAuth2 contributor, fed up with the standards process this protocol famously doesn’t have a spec.
  • Amazon’s AWS scheme.

References

HTTP series

This article is part of an ongoing series about the HTTP protocol.

If you want to follow along as I write them, you can Subscribe to my Atom feed or Mailing list.

Informational 1xx

Successful 2xx

Redirection 3xx

Client Error 4xx

Web mentions