What HTTP code to use in "Not Authenticated" and "Not authorized" cases?

Topera picture Topera · May 24, 2011 · Viewed 13.3k times · Source

I read that "401 Unauthorized" code must be used when a user:

  1. Is not logged, but login is required ("not authenticated");
  2. Is logged, but his profile don't allow to see that url ("not authorized");

According to RFC, in both cases server must return 401 code. But I need to differentiate then in my ajax requests.

Anybody have a tip to solve this?

Note: I don't want to use 403 Forbidden code, because in 403 "Authorization will not help", according to RFC.

Answer

tylerl picture tylerl · May 24, 2011

Unless you intend to use HTTP authentication, the correct response is 403 ("Forbidden").

A response code of 401 triggers the browser to display a password dialog box, and then resubmit the same request with a WWW-Authenticate header with the password data that the user supplied. That's probably not the behavior you want.

Don't get too hung up on the explanations in the RFCs -- what you really need to pay attention to are the browser and search engine side effects of the various response codes.

As for the "Authorization will not help" bit, in this case that is correct, since using HTTP authorization (which specifically means the WWW-Authenticate header), in fact, will not help.

A 403 response tells the browser that the user does not have permission to make that request, and the browser should not attempt to collect authentication data and resubmit the request. That's exactly the response you're after.