HTTP defines the status 401 Unauthorized for missing authentication, but this status only applies to HTTP authentication. What status should I return with a session cookie based system, when an unauthorized request happens?
401 Unauthorized is the status code to return when the client provides no credentials or invalid credentials. 403 Forbidden is the status code to return when a client has valid credentials but not enough privileges to perform an action on a resource.
The HTTP 402 Payment Required is a nonstandard response status code that is reserved for future use. This status code was created to enable digital cash or (micro) payment systems and would indicate that the requested content is not available until the client makes a payment.
The 4xx class of status code is intended for cases in which the client seems to have erred. Except when responding to a HEAD request, the server SHOULD include an entity containing an explanation of the error situation, and whether it is a temporary or permanent condition.
The 401 (Unauthorized) status code indicates that the request has not been applied because it lacks valid authentication credentials for the target resource... The user agent MAY repeat the request with a new or replaced Authorization header field.
Formally, 403 Forbidden is the right response. It's defined as
Authorization will not help and the request SHOULD NOT be repeated.
The confusing part may be "Authorization will not help", but they really mean "HTTP authentication" (WWW-Authenticate)
403 I believe is technically correct (and probably most effective if you are implementing a custom API / protocol).
401 is not appropriate as it refers to authorization with a WWW-Authenticate header, which a session cookie is not.
If this is a public facing website where you are trying to deny access based on a session cookie, 200 with an appropriate body to indicate that log in is needed or a 302 temporary redirect to a log in page is often best.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With