Is it OK to return an HTTP 401 status for a response to an AJAX call if you wish to convey that the user is not logged in, even though the login mechanism is form-based and not HTTP based (Basic, Digest, etc.)?
The answer here suggests that 401 should be used: https://stackoverflow.com/a/6937030/2891365
And this post shows an actual example of someone using 401 for an AJAX response: http://www.bennadel.com/blog/2228-some-thoughts-on-handling-401-unauthorized-errors-with-jquery.htm
However, RFC 2616 for HTTP/1.1 clearly states that a special header is necessary, implying that it can only be used for HTTP authentication.
10.4.2 401 Unauthorized
The request requires user authentication. The response MUST include a
WWW-Authenticate
header field (section 14.47) containing a challenge applicable to the requested resource.
I guess I can probably send a bogus header like WWW-Authenticate: WebForm
and still conform to W3C specs but it feels like it's violating the spirit of the WWW-Authenticate
header.
In the end, I cannot seem to find an authoritative source that explicitly states whether HTTP 401 is allowed for AJAX responses. Is there an authoritative source on this that I missed?
If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. 403 Forbidden: The server understood the request, but is refusing to fulfill it. From your use case, it appears that the user is not authenticated.
The 401 Unauthorized Error is an HTTP status code error that represented the request sent by the client to the server that lacks valid authentication credentials. It may be represented as 401 Unauthorized, Authorization required, HTTP error 401- Unauthorized. It represents that the request could not be authenticated.
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.
I would say it's not ok since 401 is for telling the client to provide http authentication credentials. The proper response would be 403 Forbidden, simply telling the client it's not allowed to access the resource, for whatever reason.
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