Is it OK to return a HTTP 401 for a non existent resource instead of 404 to prevent information disclosure?

Solution 1:

Actually, the W3C recommends (RFC 2616 §10.4.4 403 Forbidden) doing the opposite. If someone attempts to access a resource, but is not properly authenticated, return 404 then, rather than 403 (Forbidden). This still solves the information disclosure issue.

If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.

Thus, you would never return 403 (or 401). However, I think your solution is also reasonable.

EDIT: I think Gabe's on the right track. You would have to reconsider part of the design, but why not:

  • Not found - 404
  • User-specific insufficient permission - 404
  • General insufficient permission (no one can access) - 403
  • Not logged in - 401

Solution 2:

If usernames are sensitive information, then don't put them directly in the URI. If you use hypermedia within your representations then you can make it just as easy for an authorized client applications to navigate your api without leaking information in your URLs.

Hackable urls are great for information that you want everyone to be able to access easily. However, for a RESTful client, there is no problem using URIs that are completely opaque.

Once you have removed the direct correlation between the user and the URI, it becomes difficult to infer any information from a 401 response code.