Returning HTTP 401 status for AJAX responses witho

2019-04-21 20:28发布

问题:

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?

回答1:

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.