404 Not Found when Accessing Unauthorized/Not Found Resources?
Suppose I have Tasks with ID of 1, 2, 3, 4. User A is allowed access to 1 & 2 only.
- If he tries to access Task #3, which is unauthorized, should I give 404 or just say he's not authorized? I get this idea fr开发者_StackOverflowom logins, whether the username is valid, I always just give a generic invalid username/password combination, to prevent the user from knowing if the user/resource exists
- If he tries to access Task #5 non-existant should I give 404? or say resource not found in a generic page?
Let us say you have a site with some pages with following access rights:
- A general page, to which every one has an access.
- A page which requires a logged in user, still access by a mass public.
- An admin page, which can be accessed only by a small group of people.
- A non existent page.
So for a visitor with no rights what I suggest is to use:
403 (No permissions) with 2.
404 (Does not exists) with 3, as no general user should ever come across any link to that page so it should as well be non existent for them.
And obviously 4, a non existent page, should always result in a 404 response.
If the user doesn't have access to the task but it's OK for him to know that the task exists, use 403. If the user shouldn't even be able to determine existence of tasks that he doesn't have access to, use 404.
Trying to access a nonexistent task should definitely result in a 404 response.
You should always use an appropriate status code in an HTTP response, because it tells the browser how it should treat the response. If you return a "resource not found" error message with a 200 OK status code, the browser will think that the message is the actual page that the user requested, and will probably cache it. If you use a 404 code (or 403, etc.), the browser will understand that the page you sent back isn't actually what was requested, so it'll know not to cache it or enter its URL in the browsing history. The body of the response can still be a nice-looking HTML page with an error message for a human to read.
精彩评论