16

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?

Community
  • 1
  • 1
user193130
  • 8,009
  • 4
  • 36
  • 64

1 Answers1

2

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.

Mikael
  • 500
  • 2
  • 15
  • 2
    I was doing that but I realized I needed a way to differentiate between unauthenticated requests and authenticated-but-no-permission requests. The response content could be used but it just seems more logical to have a status code for something like this. I'm hoping for an authoritative source that specifies how best to handle this scenario. – user193130 Sep 17 '14 at 04:09
  • 1
    All forms of authentication or authorization besides HTTP Authentication are outside the scope of the HTTP protocol. Hence, while it's a common practice to implement custom security mechanisms, using cookies or whatever, there are no HTTP response codes dealing with such custom implementations more specifically. 403 means only "forbidden", not giving any specific reason. Any information related to any custom security mechanism that HTTP doesn't care about should therefore be sent in the response body. – Mikael Sep 17 '14 at 10:43
  • I was tempted to use 401 as well for this use case, but I decided to stick to 403 in the light of Mikael's answer. However, I've decided to use a custom HTTP header instead of using the response body: `X-Reason: LoginRequired`. Not sure if this fits your model @Mikael? – BenMorel Jun 22 '17 at 23:42