Subscribe to PHP Freaks RSS

401 Unauthorized

syndicated from planet-php.net on November 20, 2018

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.



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 authenticaton 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

Truncated by Planet PHP, read more at the original (another 1072 bytes)